2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.collect.Sets;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
30 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtils;
31 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
32 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
33 import org.openecomp.sdc.be.components.utils.ProxyServicePropertiesUtils;
34 import org.openecomp.sdc.be.components.validation.ComponentValidations;
35 import org.openecomp.sdc.be.config.BeEcompErrorManager;
36 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
37 import org.openecomp.sdc.be.dao.api.ActionStatus;
38 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
39 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
40 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
41 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
51 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
52 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
53 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
54 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
55 import org.openecomp.sdc.be.model.Component;
56 import org.openecomp.sdc.be.model.ComponentParametersView;
57 import org.openecomp.sdc.be.model.CapabilityDefinition;
58 import org.openecomp.sdc.be.model.InterfaceDefinition;
59 import org.openecomp.sdc.be.model.RequirementDefinition;
60 import org.openecomp.sdc.be.model.Resource;
61 import org.openecomp.sdc.be.model.Service;
62 import org.openecomp.sdc.be.model.User;
63 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
64 import org.openecomp.sdc.be.model.LifecycleStateEnum;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.DataTypeDefinition;
67 import org.openecomp.sdc.be.model.PropertyDefinition;
68 import org.openecomp.sdc.be.model.GroupDefinition;
69 import org.openecomp.sdc.be.model.InputDefinition;
70 import org.openecomp.sdc.be.model.RelationshipInfo;
71 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
72 import org.openecomp.sdc.be.model.ComponentInstance;
73 import org.openecomp.sdc.be.model.ComponentInstanceInput;
74 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
75 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
76 import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
77 import org.openecomp.sdc.be.model.jsontitan.operations.NodeFilterOperation;
78 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
79 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
80 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
81 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
82 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
83 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
84 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
85 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
86 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
87 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
88 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
89 import org.openecomp.sdc.common.api.Constants;
90 import org.openecomp.sdc.common.datastructure.Wrapper;
91 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
92 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
93 import org.openecomp.sdc.common.log.wrappers.Logger;
94 import org.openecomp.sdc.common.util.ValidationUtils;
95 import org.openecomp.sdc.exception.ResponseFormat;
96 import org.springframework.beans.factory.annotation.Autowired;
98 import java.util.ArrayList;
99 import java.util.Collection;
100 import java.util.Collections;
101 import java.util.HashMap;
102 import java.util.Iterator;
103 import java.util.List;
104 import java.util.Map;
105 import java.util.Map.Entry;
106 import java.util.Objects;
107 import java.util.Optional;
108 import java.util.Set;
109 import java.util.UUID;
110 import java.util.function.BiConsumer;
111 import java.util.stream.Collectors;
113 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
115 @org.springframework.stereotype.Component
116 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
118 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
119 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
120 public static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
121 public static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
122 public static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
123 public static final String INVALID_COMPONENT_TYPE = "invalid component type";
124 public static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
125 public static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
126 public static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
127 public static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
128 public static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
131 private IComponentInstanceOperation componentInstanceOperation;
134 private ArtifactsBusinessLogic artifactBusinessLogic;
137 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
140 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
143 private ForwardingPathOperation forwardingPathOperation;
146 private NodeFilterOperation serviceFilterOperation;
148 public ComponentInstanceBusinessLogic() {
151 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
152 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
153 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
156 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
157 List<ComponentInstanceProperty> resList = new ArrayList<>();
158 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
159 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
160 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
162 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
164 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
166 ciName = ciOp.get().getName();
167 if (ciPropList != null && !ciPropList.isEmpty()) {
168 for(ComponentInstanceProperty prop: ciPropList){
169 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
170 if(inputsValues != null && !inputsValues.isEmpty()){
171 for(GetInputValueDataDefinition inputData: inputsValues){
172 if(isGetInputValueForInput(inputData, inputId)){
173 prop.setComponentInstanceId(s);
174 prop.setComponentInstanceName(ciName);
189 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
190 List<ComponentInstanceInput> resList = new ArrayList<>();
191 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
192 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
193 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
195 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
197 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
199 ciName = ciOp.get().getName();
200 if (ciPropList != null && !ciPropList.isEmpty()) {
201 for(ComponentInstanceInput prop: ciPropList){
202 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
203 if(inputsValues != null && !inputsValues.isEmpty()){
204 for(GetInputValueDataDefinition inputData: inputsValues){
205 if(isGetInputValueForInput(inputData, inputId)){
206 prop.setComponentInstanceId(s);
207 prop.setComponentInstanceName(ciName);
222 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
223 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
225 Component origComponent = null;
226 Either<ComponentInstance, ResponseFormat> resultOp = null;
228 org.openecomp.sdc.be.model.Component containerComponent = null;
229 ComponentTypeEnum containerComponentType;
232 user = validateUserExists(userId, "create Component Instance", inTransaction);
234 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
235 if (validateValidJson.isRight()) {
236 return Either.right(validateValidJson.right().value());
239 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
240 if (validateComponentType.isRight()) {
241 return Either.right(validateComponentType.right().value());
243 containerComponentType = validateComponentType.left().value();
246 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
247 if (validateComponentExists.isRight()) {
248 return Either.right(validateComponentExists.right().value());
250 containerComponent = validateComponentExists.left().value();
253 if (ModelConverter.isAtomicComponent(containerComponent)) {
254 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
255 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
258 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
259 if (validateCanWorkOnComponent.isRight()) {
260 return Either.right(validateCanWorkOnComponent.right().value());
263 if (resourceInstance != null && containerComponentType != null) {
264 OriginTypeEnum originType = resourceInstance.getOriginType();
265 if (originType == OriginTypeEnum.ServiceProxy) {
266 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
267 if (serviceProxyOrigin.isRight()) {
268 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
269 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
271 origComponent = serviceProxyOrigin.left().value();
273 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
274 if (fillProxyRes != StorageOperationStatus.OK) {
275 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
276 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
281 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
283 if (getOriginComponentRes.isRight()) {
284 return Either.right(getOriginComponentRes.right().value());
286 origComponent = getOriginComponentRes.left().value();
291 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
292 if (lockComponent.isRight()) {
293 return Either.right(lockComponent.right().value());
296 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
297 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
302 unlockComponent(resultOp, containerComponent);
306 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
307 resourceInstance.setIsProxy(true);
308 ComponentParametersView filter = new ComponentParametersView(true);
309 filter.setIgnoreCapabilities(false);
310 filter.setIgnoreCapabiltyProperties(false);
311 filter.setIgnoreComponentInstances(false);
312 filter.setIgnoreRequirements(false);
313 filter.setIgnoreInterfaces(false);
314 filter.setIgnoreProperties(false);
315 filter.setIgnoreInputs(false);
316 Either<Component, StorageOperationStatus> serviceRes =
317 toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
318 if (serviceRes.isRight()) {
319 return serviceRes.right().value();
321 Component service = serviceRes.left().value();
322 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
323 resourceInstance.setCapabilities(capabilities);
324 Map<String, List<RequirementDefinition>> req = service.getRequirements();
325 resourceInstance.setRequirements(req);
327 Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
328 if(MapUtils.isNotEmpty(serviceInterfaces)) {
329 serviceInterfaces.forEach(resourceInstance::addInterface);
333 resourceInstance.setProperties(ProxyServicePropertiesUtils.getProperties(service));
335 List<InputDefinition> serviceInputs = service.getInputs();
336 resourceInstance.setInputs(serviceInputs);
338 String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
339 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
340 int lastIndexOf = toscaResourceName.lastIndexOf('.');
341 if (lastIndexOf != -1) {
342 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
343 resourceInstance.setToscaComponentName(proxyToscaName);
345 resourceInstance.setName(name);
346 resourceInstance.setIsProxy(true);
347 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
348 resourceInstance.setSourceModelName(service.getName());
349 resourceInstance.setSourceModelUuid(service.getUUID());
350 resourceInstance.setSourceModelUid(service.getUniqueId());
351 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
352 resourceInstance.setDescription("A Proxy for Service " + service.getName());
353 resourceInstance.setComponentVersion(service.getVersion());
355 return StorageOperationStatus.OK;
358 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
360 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
361 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
362 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
364 User user = validateUserExists(userId, "create And Associate RI To RI", false);
366 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
367 if (validateComponentType.isRight()) {
368 return Either.right(validateComponentType.right().value());
371 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
373 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
374 if (validateComponentExists.isRight()) {
375 return Either.right(validateComponentExists.right().value());
377 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
379 if (ModelConverter.isAtomicComponent(containerComponent)) {
380 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
381 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
384 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
385 if (validateCanWorkOnComponent.isRight()) {
386 return Either.right(validateCanWorkOnComponent.right().value());
389 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
390 if (lockComponent.isRight()) {
391 return Either.right(lockComponent.right().value());
395 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
396 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
398 if (eitherResourceName.isRight()) {
399 resultOp = Either.right(eitherResourceName.right().value());
402 Component origComponent = eitherResourceName.left().value();
404 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
405 if (result.isRight()) {
406 log.debug("Failed to create resource instance {}", containerComponentId);
407 resultOp = Either.right(result.right().value());
412 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
413 ComponentInstance resResourceInfo = result.left().value();
414 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
415 associationInfo.setFromNode(resResourceInfo.getUniqueId());
417 associationInfo.setToNode(resResourceInfo.getUniqueId());
420 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
421 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
422 if (resultReqCapDef.isLeft()) {
423 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
424 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
425 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
426 resultOp = Either.left(resInfo);
430 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
431 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
436 unlockComponent(resultOp, containerComponent);
440 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
441 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
444 private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
445 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
448 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
449 Either<Component, ResponseFormat> eitherResponse;
450 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
451 if (eitherComponent.isRight()) {
452 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
453 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
455 eitherResponse = Either.left(eitherComponent.left().value());
457 return eitherResponse;
460 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
461 Either<ComponentInstance, ResponseFormat> resultOp;
463 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
465 if (result.isRight()) {
466 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
467 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
471 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
472 Component updatedComponent = result.left().value().getLeft();
473 Map<String, String> existingEnvVersions = new HashMap<>();
474 // TODO existingEnvVersions ??
475 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
476 if (addComponentInstanceArtifacts.isRight()) {
477 log.debug("Failed to create component instance {}", componentInstance.getName());
478 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
482 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
483 if (!updatedInstanceOptional.isPresent()) {
484 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
485 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
488 resultOp = Either.left(updatedInstanceOptional.get());
493 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
494 * @param containerComponent
495 * @param componentInstance
496 * @param originComponent
498 * @param existingEnvVersions
501 protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
503 log.debug("add artifacts to resource instance");
504 List<GroupDefinition> filteredGroups = null;
505 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
506 if (!ActionStatus.OK.equals(status)) {
507 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
508 return Either.right(resultOp);
510 StorageOperationStatus artStatus;
511 // generate heat_env if necessary
512 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
513 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
515 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
516 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
518 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
519 String type = artifact.getArtifactType();
520 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
521 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
523 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
526 if (artifact.checkEsIdExist()) {
527 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
528 componentInstance.getName(), user, containerComponent, existingEnvVersions);
529 if (createHeatEnvPlaceHolder.isRight()) {
530 return Either.right(createHeatEnvPlaceHolder.right().value());
532 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
534 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
536 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
537 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
539 if (CollectionUtils.isNotEmpty(filteredGroups)) {
540 for (GroupDefinition groupInstance : filteredGroups) {
541 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
542 if (op.isPresent()) {
543 List<ArtifactDefinition> artifactsUid;
544 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
545 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
547 artifactsUid = new ArrayList<>();
549 artifactsUid.add(artifactDefinition);
550 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
557 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
558 if (artStatus != StorageOperationStatus.OK) {
559 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
560 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
563 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
564 if (result != StorageOperationStatus.OK) {
565 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
566 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
568 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
571 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
572 if (artStatus != StorageOperationStatus.OK) {
573 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
574 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
577 componentInstance.setArtifacts(originComponent.getArtifacts());
578 return Either.left(ActionStatus.OK);
581 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
582 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
584 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
585 if (getResourceDeploymentArtifacts.isRight()) {
586 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
587 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
588 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
589 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
592 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
595 if (!deploymentArtifacts.isEmpty()) {
596 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
597 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
598 if (!artifact.getValue().checkEsIdExist()) {
599 tempDeploymentArtifacts.remove(artifact.getKey());
603 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
606 return ActionStatus.OK;
609 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
610 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
613 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
614 boolean needLock, boolean createNewTransaction) {
616 validateUserExists(userId, "update Component Instance", inTransaction);
618 Either<ComponentInstance, ResponseFormat> resultOp = null;
620 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
621 if (validateComponentType.isRight()) {
622 return Either.right(validateComponentType.right().value());
625 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
627 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
628 if (validateComponentExists.isRight()) {
629 return Either.right(validateComponentExists.right().value());
631 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
633 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
634 if (validateCanWorkOnComponent.isRight()) {
635 return Either.right(validateCanWorkOnComponent.right().value());
637 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
638 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
639 if (validateParentStatus.isRight()) {
640 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
641 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
644 if (!validateParentStatus.left().value()) {
645 resultOp = Either.right(
646 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
651 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
652 if (lockComponent.isRight()) {
653 return Either.right(lockComponent.right().value());
658 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
660 if (eitherResourceName.isRight()) {
661 resultOp = Either.right(eitherResourceName.right().value());
664 Component origComponent = eitherResourceName.left().value();
666 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
671 unlockComponent(resultOp, containerComponent);
675 // New Multiple Instance Update API
676 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
678 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
679 org.openecomp.sdc.be.model.Component containerComponent = null;
681 validateUserExists(userId, "update Component Instance", true);
683 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
684 if (validateComponentType.isRight()) {
685 return Either.right(validateComponentType.right().value());
688 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
690 ComponentParametersView componentFilter = new ComponentParametersView();
691 componentFilter.disableAll();
692 componentFilter.setIgnoreUsers(false);
693 componentFilter.setIgnoreComponentInstances(false);
694 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
695 if (validateComponentExists.isRight()) {
696 return Either.right(validateComponentExists.right().value());
699 containerComponent = validateComponentExists.left().value();
701 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
702 if (validateCanWorkOnComponent.isRight()) {
703 return Either.right(validateCanWorkOnComponent.right().value());
706 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
708 for (ComponentInstance componentInstance : componentInstanceList) {
709 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
710 if (!validateParent) {
711 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
712 containerComponentId));
719 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
720 if (lockComponent.isRight()) {
721 return Either.right(lockComponent.right().value());
725 List<ComponentInstance> updatedList = new ArrayList<>();
726 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
727 List<ComponentInstance> listForUpdate = new ArrayList<>();
728 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
729 containerComponent.setComponentInstances(componentInstanceList);
731 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
732 while (iterator.hasNext()) {
733 ComponentInstance origInst = iterator.next();
734 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
735 if (op.isPresent()) {
736 ComponentInstance updatedCi = op.get();
737 updatedCi = buildComponentInstance(updatedCi, origInst);
739 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
741 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
742 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
745 listForUpdate.add(updatedCi);
747 listForUpdate.add(origInst);
749 containerComponent.setComponentInstances(listForUpdate);
751 if (resultOp == null) {
752 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
753 if (updateStatus.isRight()) {
754 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
755 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
758 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
759 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
760 if (op.isPresent()) {
761 updatedList.add(updatedInstance);
767 resultOp = Either.left(updatedList);
772 unlockComponent(resultOp, containerComponent);
777 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
778 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
781 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
782 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
783 return ComponentTypeEnum.SERVICE_INSTANCE;
785 return ComponentTypeEnum.RESOURCE_INSTANCE;
789 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
790 ComponentInstance componentInstance) {
792 Either<ComponentInstance, ResponseFormat> resultOp = null;
793 Optional<ComponentInstance> componentInstanceOptional = null;
794 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
795 ComponentInstance oldComponentInstance = null;
796 boolean isNameChanged = false;
798 if (resultOp == null) {
799 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
800 if (!componentInstanceOptional.isPresent()) {
801 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
802 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
805 if (resultOp == null) {
806 oldComponentInstance = componentInstanceOptional.get();
807 String newInstanceName = componentInstance.getName();
808 if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
809 isNameChanged = true;
810 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
812 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
813 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
815 if(!DirectivesUtils.isValid(componentInstance.getDirectives())) {
816 final String directivesStr =
817 componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
818 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
819 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
820 oldComponentInstance.getName(), newInstanceName ,
822 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.DIRECTIVES_INVALID_VALUE,
826 String newInstanceName = componentInstance.getName();
827 String oldInstanceName = null;
828 if (resultOp == null) {
829 oldComponentInstance = componentInstanceOptional.get();
830 newInstanceName = componentInstance.getName();
831 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
832 if (updateRes.isRight()) {
833 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
834 updateRes.right().value());
835 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
837 // region - Update instance Groups
839 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
840 if (result.isRight())
841 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
842 if (containerComponent instanceof Service) {
843 Either<ComponentInstance, ResponseFormat> renameEither =
844 renameServiceFilter((Service) containerComponent, newInstanceName,
846 if (renameEither.isRight()) {
854 if (resultOp == null) {
855 String newInstanceId = updateRes.left().value().getRight();
856 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
858 if (!updatedInstanceOptional.isPresent()) {
859 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
860 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
862 resultOp = Either.left(updatedInstanceOptional.get());
866 if (resultOp == null) {
867 resultOp = Either.left(componentInstanceOptional.get());
873 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(Service containerComponent,
874 String newInstanceName, String oldInstanceName) {
876 Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
877 ServiceFilterUtils.getRenamedNodesFilter((Service) containerComponent,
878 oldInstanceName, newInstanceName);
879 for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){
880 Either<CINodeFilterDataDefinition, StorageOperationStatus>
881 renameEither = serviceFilterOperation.updateNodeFilter(
882 containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
883 if (renameEither.isRight()){
884 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
885 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
886 containerComponent.getName(), null));
890 return Either.left(null);
895 * The normalized old vf name
896 * @param newNormailzedPrefix-
897 * The normalized new vf name
898 * @param qualifiedGroupInstanceName-
899 * old Group Instance Name
901 // modify group names
902 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
903 if (qualifiedGroupInstanceName == null) {
904 log.info("CANNOT change group name ");
907 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
908 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
909 return qualifiedGroupInstanceName;
912 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
913 oldComponentInstance.setName(newComponentInstance.getName());
914 oldComponentInstance.setModificationTime(System.currentTimeMillis());
915 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
916 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
917 if (oldComponentInstance.getGroupInstances() != null)
918 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
919 return oldComponentInstance;
922 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
924 validateUserExists(userId, "delete Component Instance", false);
926 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
927 if (validateComponentType.isRight()) {
928 return Either.right(validateComponentType.right().value());
931 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
932 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
933 if (validateComponentExists.isRight()) {
934 return Either.right(validateComponentExists.right().value());
936 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
937 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
938 if (validateCanWorkOnComponent.isRight()) {
939 return Either.right(validateCanWorkOnComponent.right().value());
942 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
943 if (lockComponent.isRight()) {
944 return Either.right(lockComponent.right().value());
947 Either<ComponentInstance, ResponseFormat> resultOp = null;
949 if (containerComponent instanceof Service) {
950 ComponentInstance componentInstance = containerComponent.getComponentInstanceById(componentInstanceId).get();
951 Either<String, StorageOperationStatus> deleteServiceFilterEither =
952 serviceFilterOperation.deleteNodeFilter((Service) containerComponent, componentInstanceId);
953 if (deleteServiceFilterEither.isRight()) {
954 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
955 containerComponentType);
957 return Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
959 resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent,
960 componentInstance, ComponentTypeEnum.SERVICE, userId);
961 if (resultOp.isRight()) {
966 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
967 if (resultOp.isRight()){
970 Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
971 containerComponentType, resultOp);
972 if (deleteEither.isRight()){
978 unlockComponent(resultOp, containerComponent);
982 public Either<ComponentInstance, ResponseFormat> deleteServiceFiltersRelatedTobeDeletedComponentInstance(
983 Service service, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String userId) {
984 if (containerComponentType.equals(ComponentTypeEnum.SERVICE)) {
985 Set<String> serviceFiltersIDsToBeDeleted =
986 getServiceFiltersRelatedToComponentInstance(service.getUniqueId(), componentInstance);
987 if (!serviceFiltersIDsToBeDeleted.isEmpty()) {
988 Set<String> ids = service.getComponentInstances().stream()
989 .filter(ci -> serviceFiltersIDsToBeDeleted
990 .contains(ci.getName()))
991 .map(ComponentInstance::getUniqueId)
992 .collect(Collectors.toSet());
993 Either<Set<String>, StorageOperationStatus> deleteServiceFiltersEither =
994 serviceFilterOperation.deleteNodeFilters(service, ids);
995 if (deleteServiceFiltersEither.isRight()) {
996 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFiltersEither.right().value(),
997 containerComponentType);
998 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1000 for (String id : ids) {
1001 final Optional<ComponentInstance> componentInstanceById = service.getComponentInstanceById(id);
1002 if (!componentInstanceById.isPresent()){
1003 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1005 ComponentInstance ci = componentInstanceById.get();
1006 List<String> directives = ci.getDirectives();
1007 directives.remove(DirectivesUtils.SELECTABLE);
1008 ci.setDirectives(directives);
1009 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
1010 updateComponentInstanceMetadata(ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUniqueId(),
1011 ci.getUniqueId(), userId, ci, true, false, false);
1012 if (componentInstanceResponseFormatEither.isRight()) {
1013 return componentInstanceResponseFormatEither;
1018 return Either.left(componentInstance);
1023 private Set<String> getServiceFiltersRelatedToComponentInstance(String containerComponentId,
1024 ComponentInstance componentInstance) {
1025 ComponentParametersView filter = new ComponentParametersView(true);
1026 filter.setIgnoreComponentInstances(false);
1027 Either<Service, StorageOperationStatus> serviceFilterOrigin =
1028 toscaOperationFacade.getToscaElement(containerComponentId, filter);
1029 final Service service = serviceFilterOrigin.left().value();
1030 final Set<String> nodesFiltersToBeDeleted = ServiceFilterUtils.getNodesFiltersToBeDeleted(service,
1032 return nodesFiltersToBeDeleted;
1036 public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
1037 Either<ComponentInstance, ResponseFormat> resultOp) {
1038 if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
1039 final ComponentInstance componentInstance = resultOp.left().value();
1040 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1041 if (!pathIDsToBeDeleted.isEmpty()) {
1042 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
1043 pathIDsToBeDeleted);
1044 if(deleteForwardingPathsEither.isRight()) {
1045 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1054 private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
1056 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1057 if(storageStatus.isRight()) {
1058 return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
1060 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
1061 Sets.newHashSet(pathIdsToDelete));
1063 if(result.isRight()) {
1064 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
1066 return Either.left(result.left().value());
1069 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
1070 ComponentParametersView filter = new ComponentParametersView(true);
1071 filter.setIgnoreForwardingPath(false);
1072 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
1073 .getToscaElement(containerComponentId, filter);
1074 Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
1075 List<String> pathIDsToBeDeleted = new ArrayList<>();
1077 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
1078 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1080 return pathIDsToBeDeleted;
1083 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
1084 String componentInstanceId){
1085 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
1086 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
1087 elementDataDefinition.getToNode()
1088 .equalsIgnoreCase(componentInstanceId));
1092 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
1094 Either<ComponentInstance, ResponseFormat> resultOp = null;
1095 ComponentInstance deletedInstance = null;
1096 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1098 if (deleteRes.isRight()) {
1099 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1100 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1101 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
1103 if (resultOp == null) {
1104 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1105 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1106 resultOp = Either.left(deletedInstance);
1108 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
1109 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
1110 for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
1111 Map<String, String> members = currGroup.getMembers();
1112 if (members != null && members.containsKey(deletedInstance.getName())) {
1113 members.remove(deletedInstance.getName());
1114 groupsToUpdate.add(currGroup);
1117 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
1118 if (updateGroupsRes.isRight()) {
1119 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
1120 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
1121 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
1124 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1125 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1126 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1127 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1128 if (deleteInputsRes != StorageOperationStatus.OK) {
1129 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1130 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
1137 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1138 ComponentInstance foundInstance = null;
1139 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1140 if (instance.getUniqueId().equals(componentInstanceId)) {
1141 foundInstance = instance;
1142 containerComponent.getComponentInstances().remove(instance);
1146 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1147 return foundInstance;
1150 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1151 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1152 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1156 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1157 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1160 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1161 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1164 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1165 boolean createNewTransaction) {
1167 validateUserExists(userId, "associate Ri To RI", inTransaction);
1169 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1171 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1172 if (validateComponentExists.isRight()) {
1173 return Either.right(validateComponentExists.right().value());
1175 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1177 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1178 if (validateCanWorkOnComponent.isRight()) {
1179 return Either.right(validateCanWorkOnComponent.right().value());
1182 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1184 if (lockComponent.isRight()) {
1185 return Either.right(lockComponent.right().value());
1191 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1197 unlockComponent(resultOp, containerComponent);
1201 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1203 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1204 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1206 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1208 if (result.isLeft()) {
1209 log.debug("Enty on graph is created.");
1210 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1211 resultOp = Either.left(requirementCapabilityRelDef);
1215 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1216 String fromNameOrId = "";
1217 String toNameOrId = "";
1218 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1219 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1221 toNameOrId = requirementDef.getFromNode();
1222 fromNameOrId = requirementDef.getFromNode();
1223 if (fromResult.isLeft()) {
1224 fromNameOrId = fromResult.left().value().getName();
1226 if (toResult.isLeft()) {
1227 toNameOrId = toResult.left().value().getName();
1230 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1238 * @param componentId
1240 * @param requirementDefList
1241 * @param componentTypeEnum
1244 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1247 List<RequirementCapabilityRelDef> requirementDefList,
1248 ComponentTypeEnum componentTypeEnum) {
1250 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1251 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1252 if (validateResponse.isRight()) {
1256 Component containerComponent = validateResponse.left().value();
1257 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1258 if (lockComponent.isRight()) {
1262 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1263 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = dissociateRIFromRI(
1264 componentId, requirementDef, containerComponent);
1266 if (actionResponse.isLeft()) {
1267 delOkResult.add(actionResponse.left().value());
1271 unlockComponent(validateResponse, containerComponent);
1276 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1277 String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1278 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1279 if(validateResponse.isRight())
1281 return Either.right(validateResponse.right().value());
1283 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = null;
1284 Component containerComponent = validateResponse.left().value();
1285 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1286 if (lockComponent.isRight()) {
1287 return Either.right(lockComponent.right().value());
1290 actionResponse = dissociateRIFromRI(
1291 componentId, requirementDef,containerComponent);
1293 unlockComponent(validateResponse, containerComponent);
1295 return actionResponse;
1298 private Either<Component, ResponseFormat> validateDissociateRI(
1299 String componentId, String userId, ComponentTypeEnum componentTypeEnum) {
1300 validateUserExists(userId, "dissociate RI From RI", false);
1303 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1304 if (validateComponentExists.isRight()) {
1305 return Either.right(validateComponentExists.right().value());
1307 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1309 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1310 if (validateCanWorkOnComponent.isRight()) {
1311 return Either.right(validateCanWorkOnComponent.right().value());
1313 return Either.left(containerComponent);
1316 private Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1317 String componentId, RequirementCapabilityRelDef requirementDef, Component containerComponent) {
1319 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1320 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1321 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(
1322 componentId, requirementDef);
1323 if (result.isLeft()) {
1324 log.debug("Enty on graph is created.");
1325 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1326 resultOp = Either.left(requirementCapabilityRelDef);
1331 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1332 String fromNameOrId = "";
1333 String toNameOrId = "";
1334 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(
1335 containerComponent, requirementDef.getFromNode());
1336 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(
1337 containerComponent, requirementDef.getToNode());
1339 toNameOrId = requirementDef.getFromNode();
1340 fromNameOrId = requirementDef.getFromNode();
1341 if (fromResult.isLeft()) {
1342 fromNameOrId = fromResult.left().value().getName();
1344 if (toResult.isLeft()) {
1345 toNameOrId = toResult.left().value().getName();
1349 .right(componentsUtils.getResponseFormat(
1350 componentsUtils.convertFromStorageResponseForResourceInstance(
1351 result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1357 * Allows to get relation contained in specified component according to received Id
1358 * @param componentId
1361 * @param componentTypeEnum
1364 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1366 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1368 org.openecomp.sdc.be.model.Component containerComponent = null;
1369 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1370 RequirementCapabilityRelDef foundRelation = null;
1372 validateUserExists(userId, "get relation by Id", false);
1374 if(resultOp == null){
1375 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1376 if (validateComponentExists.isRight()) {
1377 resultOp = Either.right(validateComponentExists.right().value());
1380 if(resultOp == null){
1381 containerComponent = validateComponentExists.left().value();
1382 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1383 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1384 if(foundRelation == null){
1385 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1386 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1387 resultOp = Either.right(responseFormat);
1390 if(resultOp == null){
1391 resultOp = setRelatedCapability(foundRelation, containerComponent);
1393 if(resultOp.isLeft()){
1394 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1396 } catch (Exception e) {
1397 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1398 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1403 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1404 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1405 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1406 return relationship;
1412 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1413 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1414 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1415 String instanceId = foundRelation.getFromNode();
1416 Optional<RequirementDefinition> foundRequirement;
1417 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1418 if(!instance.isPresent()){
1419 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1420 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1421 result = Either.right(responseFormat);
1424 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1425 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1426 if(foundRequirement.isPresent()){
1427 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1428 result = Either.left(foundRelation);
1433 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1434 if(getfulfilledRequirementRes.isRight()){
1435 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1436 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1437 result = Either.right(responseFormat);
1439 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1443 result = Either.left(foundRelation);
1448 private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1449 return req.getName().equals(relationshipInfo.getRequirement()) &&
1450 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1451 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1454 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1455 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1456 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1457 String instanceId = foundRelation.getToNode();
1458 Optional<CapabilityDefinition> foundCapability;
1459 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1460 if(!instance.isPresent()){
1461 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1462 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1463 result = Either.right(responseFormat);
1466 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1467 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1468 if(foundCapability.isPresent()){
1469 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1470 result = Either.left(foundRelation);
1475 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1476 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1477 if(getfulfilledRequirementRes.isRight()){
1478 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1479 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1480 result = Either.right(responseFormat);
1482 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1486 result = Either.left(foundRelation);
1491 private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1492 return cap.getName().equals(relationshipInfo.getCapability()) &&
1493 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1494 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1497 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1498 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1499 Either<ComponentInstanceProperty, ResponseFormat> result;
1500 if (eitherAttribute.isLeft()) {
1501 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1502 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1504 result = Either.left(instanceAttribute);
1507 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1509 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1511 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1517 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1519 Either<ComponentInstanceProperty, ResponseFormat> result;
1521 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1522 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1523 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1525 if (!errorWrapper.isEmpty()) {
1526 result = Either.right(errorWrapper.getInnerElement());
1528 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1529 if (eitherAttribute.isLeft()) {
1530 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1531 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1532 result = Either.left(instanceAttribute);
1535 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1537 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1538 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1546 * Create Or Updates Attribute Instance
1548 * @param componentTypeEnum
1549 * @param componentId
1550 * @param resourceInstanceId
1555 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1556 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1557 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1559 validateUserExist(userId, "create Or Update Attribute Value");
1560 if (errorWrapper.isEmpty()) {
1561 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1563 if (errorWrapper.isEmpty()) {
1564 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1566 if (errorWrapper.isEmpty()) {
1567 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1571 if (errorWrapper.isEmpty()) {
1572 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1574 result = createAttributeValue(attribute, resourceInstanceId);
1576 result = updateAttributeValue(attribute, resourceInstanceId);
1579 result = Either.right(errorWrapper.getInnerElement());
1585 if (result == null || result.isRight()) {
1586 titanDao.rollback();
1591 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1595 private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1596 return StringUtils.isNotEmpty(property.getValue())
1597 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1598 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1601 // US833308 VLI in service - specific network_role property value logic
1602 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1603 for (ComponentInstanceProperty property: properties) {
1604 if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1605 ComponentParametersView componentParametersView = new ComponentParametersView();
1606 componentParametersView.disableAll();
1607 componentParametersView.setIgnoreComponentInstances(false);
1608 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1609 if (getServiceResult.isRight()) {
1610 return getServiceResult.right().value();
1612 Component service = getServiceResult.left().value();
1613 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1614 if (!getInstance.isPresent()) {
1615 return StorageOperationStatus.NOT_FOUND;
1617 String prefix = service.getSystemName() + ".";
1618 String value = property.getValue();
1619 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1620 property.setValue(prefix + value);
1624 return StorageOperationStatus.OK;
1627 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1629 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1631 /*-------------------------------Validations---------------------------------*/
1633 validateUserExists(userId, "create Or Update Properties Values", false);
1635 if (componentTypeEnum == null) {
1636 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1637 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1640 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1642 if (getResourceResult.isRight()) {
1643 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1644 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1647 Component containerComponent = getResourceResult.left().value();
1649 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1650 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1651 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1654 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1655 if (resourceInstanceStatus.isRight()) {
1656 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1659 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1660 // specific property value logic US833308
1661 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1662 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1663 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1667 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1668 if (lockStatus != StorageOperationStatus.OK) {
1669 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1670 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1675 for (ComponentInstanceProperty property: properties) {
1676 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1677 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1678 responseFormat -> Either.right(responseFormat));
1681 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1682 if (updateContainerRes.isRight()) {
1683 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1684 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1687 resultOp = Either.left(properties);
1691 if (resultOp == null || resultOp.isRight()) {
1692 titanDao.rollback();
1697 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1701 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1702 String capabilityType, String capabilityName) {
1703 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1704 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
1705 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1706 String capKey = sb.toString();
1708 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1709 .orElse(Collections.emptyMap());
1710 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
1711 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1712 if (cap.isPresent()) {
1713 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1714 if (capProperties != null) {
1715 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1716 StorageOperationStatus status;
1717 if (instanceProperty.isPresent()) {
1718 instanceProperty.get().setValue(newValue);
1719 List<String> path = new ArrayList<>();
1720 path.add(componentInstanceUniqueId);
1722 instanceProperty.get().setPath(path);
1723 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1724 if (status != StorageOperationStatus.OK) {
1725 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1726 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1729 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1735 return componentsUtils.getResponseFormat(ActionStatus.OK);
1738 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1739 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1740 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1741 StorageOperationStatus status;
1742 instanceProperty.get().setValue(newValue);
1743 if (instanceProperty.isPresent()) {
1744 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1746 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1748 if (status != StorageOperationStatus.OK) {
1749 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1750 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1752 List<String> path = new ArrayList<>();
1753 path.add(foundResourceInstance.getUniqueId());
1754 property.setPath(path);
1756 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1757 return componentsUtils.getResponseFormat(ActionStatus.OK);
1760 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1761 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1762 if (allDataTypesEither.isRight()) {
1763 TitanOperationStatus status = allDataTypesEither.right().value();
1764 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1765 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1767 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1768 String innerType = null;
1769 String propertyType = property.getType();
1770 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1771 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1773 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1774 SchemaDefinition def = property.getSchema();
1776 log.debug("Schema doesn't exists for property of type {}", type);
1777 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1779 PropertyDataDefinition propDef = def.getProperty();
1780 if (propDef == null) {
1781 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1782 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1784 innerType = propDef.getType();
1786 // Specific Update Logic
1787 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1788 String newValue = property.getValue();
1789 if (isValid.isRight()) {
1790 Boolean res = isValid.right().value();
1792 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1795 Object object = isValid.left().value();
1796 if (object != null) {
1797 newValue = object.toString();
1801 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1802 if (pair.getRight() != null && pair.getRight() == false) {
1803 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1804 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1807 return Either.left(newValue);
1810 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1811 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1812 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1813 StorageOperationStatus status;
1814 if (instanceProperty.isPresent()) {
1815 instanceProperty.get().setValue(input.getValue());
1816 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1818 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1820 if (status != StorageOperationStatus.OK) {
1821 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1822 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1824 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1825 return componentsUtils.getResponseFormat(ActionStatus.OK);
1828 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1830 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1832 validateUserExists(userId, "create Or Update Property Value", false);
1834 if (componentTypeEnum == null) {
1835 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1836 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1839 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1841 if (getResourceResult.isRight()) {
1842 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1843 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1846 Component containerComponent = getResourceResult.left().value();
1848 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1849 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1850 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1853 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1854 if (resourceInstanceStatus.isRight()) {
1855 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1859 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1862 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1863 if (lockStatus != StorageOperationStatus.OK) {
1864 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1865 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1869 for (ComponentInstanceInput input: inputs) {
1870 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1871 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1875 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1877 if (updateContainerRes.isRight()) {
1878 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1879 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1882 resultOp = Either.left(inputs);
1886 if (resultOp == null || resultOp.isRight()) {
1887 titanDao.rollback();
1892 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1897 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1900 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1902 validateUserExists(userId, "create Or Update Property Value", false);
1904 if (componentTypeEnum == null) {
1905 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1906 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1910 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1911 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1912 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1916 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1917 if (lockStatus != StorageOperationStatus.OK) {
1918 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1919 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1923 String propertyValueUid = property.getValueUniqueUid();
1925 if (propertyValueUid == null) {
1927 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1929 if (counterRes.isRight()) {
1930 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1931 StorageOperationStatus status = counterRes.right().value();
1932 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1933 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1935 Integer index = counterRes.left().value();
1936 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1938 if (result.isLeft()) {
1939 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1940 ComponentInstanceProperty instanceProperty = result.left().value();
1942 resultOp = Either.left(instanceProperty);
1945 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1947 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1949 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1953 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1955 if (result.isLeft()) {
1956 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1957 ComponentInstanceProperty instanceProperty = result.left().value();
1959 resultOp = Either.left(instanceProperty);
1962 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1964 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1966 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1969 if (resultOp.isLeft()) {
1970 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1971 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1972 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1974 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1981 if (resultOp == null || resultOp.isRight()) {
1982 titanDao.rollback();
1987 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1992 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1994 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1996 validateUserExists(userId, "create Or Update Input Value", false);
1998 if (componentTypeEnum == null) {
1999 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2000 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2004 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2005 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2006 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2010 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2011 if (lockStatus != StorageOperationStatus.OK) {
2012 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2013 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2017 String propertyValueUid = inputProperty.getValueUniqueUid();
2018 if (propertyValueUid == null) {
2020 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
2022 if (counterRes.isRight()) {
2023 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
2024 StorageOperationStatus status = counterRes.right().value();
2025 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2026 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2028 Integer index = counterRes.left().value();
2029 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
2031 if (result.isLeft()) {
2032 log.debug("Property value was added to resource instance {}", resourceInstanceId);
2033 ComponentInstanceInput instanceProperty = result.left().value();
2035 resultOp = Either.left(instanceProperty);
2039 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
2041 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2043 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2049 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
2051 if (result.isLeft()) {
2052 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
2053 ComponentInstanceInput instanceProperty = result.left().value();
2055 resultOp = Either.left(instanceProperty);
2059 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
2061 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2063 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2070 if (resultOp == null || resultOp.isRight()) {
2071 titanDao.rollback();
2076 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2081 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
2083 validateUserExists(userId, "delete Property Value", false);
2085 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2087 if (componentTypeEnum == null) {
2088 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2089 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2093 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2094 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2095 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2099 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2100 if (lockStatus != StorageOperationStatus.OK) {
2101 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2102 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2106 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2108 if (result.isLeft()) {
2109 log.debug("Property value {} was removed from graph.", propertyValueId);
2110 ComponentInstanceProperty instanceProperty = result.left().value();
2112 resultOp = Either.left(instanceProperty);
2116 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2118 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2120 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2126 if (resultOp == null || resultOp.isRight()) {
2127 titanDao.rollback();
2132 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2137 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
2139 Either<Component, ResponseFormat> eitherResponse = null;
2140 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
2141 Component component;
2142 ResponseFormat errorResponse;
2143 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2144 if (getComponentRes.isRight()) {
2145 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2146 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2147 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2148 eitherResponse = Either.right(errorResponse);
2150 if (eitherResponse == null) {
2151 component = getComponentRes.left().value();
2152 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2153 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2154 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
2155 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
2156 eitherResponse = Either.right(errorResponse);
2159 if (eitherResponse == null) {
2160 eitherResponse = Either.left(getComponentRes.left().value());
2162 return eitherResponse;
2165 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2166 String containerComponentId,
2167 String componentInstanceId,
2168 ComponentInstance newComponentInstance) {
2169 Either<Set<String>, ResponseFormat> resultOp;
2170 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2171 if (validateComponentType.isRight()) {
2172 return Either.right(validateComponentType.right().value());
2174 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2175 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2178 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
2179 validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2180 if (validateComponentExists.isRight()) {
2181 return Either.right(validateComponentExists.right().value());
2183 Component containerComponent = validateComponentExists.left().value();
2185 //Fetch current component instance
2186 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2187 getResourceInstanceById(containerComponent, componentInstanceId);
2188 if (eitherResourceInstance.isRight()) {
2189 resultOp = Either.right(componentsUtils.getResponseFormat(
2190 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2193 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2195 //Check whether new componentInstance exists
2196 String resourceId = newComponentInstance.getComponentUid();
2197 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2198 if (componentExistsRes.isRight()) {
2199 log.debug("Failed to find resource {} ", resourceId);
2200 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2201 (componentExistsRes.right().value()), resourceId));
2203 } else if (!componentExistsRes.left().value()) {
2204 log.debug("The resource {} not found ", resourceId);
2205 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2209 //Fetch component using new component instance uid
2210 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2211 if (eitherResourceName.isRight()) {
2212 resultOp = Either.right(eitherResourceName.right().value());
2215 Component updatedContainerComponent=eitherResourceName.left().value();
2216 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2217 currentResourceInstance, updatedContainerComponent);
2218 resultOp=Either.left(toDeleteForwardingPaths);
2223 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2224 Component updatedContainerComponent) {
2225 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2226 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2228 Service service = (Service) containerComponent;
2229 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2231 return forwardingPathUtils.
2232 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2235 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2236 ComponentParametersView componentParametersView = new ComponentParametersView();
2237 componentParametersView.setIgnoreCapabiltyProperties(false);
2238 componentParametersView.setIgnoreForwardingPath(false);
2239 return componentParametersView;
2242 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2244 User user = validateUserExists(userId, "change Component Instance Version", false);
2246 Either<ComponentInstance, ResponseFormat> resultOp = null;
2248 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2249 if (validateComponentType.isRight()) {
2250 return Either.right(validateComponentType.right().value());
2253 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2254 ComponentParametersView componentParametersView = new ComponentParametersView();
2255 componentParametersView.setIgnoreCapabiltyProperties(false);
2256 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2257 if (validateComponentExists.isRight()) {
2258 return Either.right(validateComponentExists.right().value());
2260 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2262 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2263 if (validateCanWorkOnComponent.isRight()) {
2264 return Either.right(validateCanWorkOnComponent.right().value());
2267 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2268 if (resourceInstanceStatus.isRight()) {
2269 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2273 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2275 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2278 public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2279 ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
2280 Either<ComponentInstance, ResponseFormat> resultOp = null;
2281 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2283 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2284 String containerComponentId = containerComponent.getUniqueId();
2285 String componentInstanceId = currentResourceInstance.getUniqueId();
2286 if (lockComponent.isRight()) {
2287 return Either.right(lockComponent.right().value());
2293 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2294 resultOp = Either.left(currentResourceInstance);
2298 String resourceId = newComponentInstance.getComponentUid();
2302 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2303 if (componentExistsRes.isRight()) {
2304 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2305 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2307 } else if (!componentExistsRes.left().value()) {
2308 log.debug("The resource {} not found ", resourceId);
2309 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2313 Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2315 if (eitherOriginComponent.isRight()) {
2316 resultOp = Either.right(eitherOriginComponent.right().value());
2319 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2320 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2321 if (resultOp.isRight()) {
2322 log.debug("failed to delete resource instance {}", resourceId);
2325 ComponentInstance resResourceInfo = resultOp.left().value();
2326 Component origComponent = null;
2327 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2328 if (originType == OriginTypeEnum.ServiceProxy) {
2329 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2330 if (serviceProxyOrigin.isRight()) {
2331 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2332 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2334 origComponent = serviceProxyOrigin.left().value();
2336 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2338 if (fillProxyRes != StorageOperationStatus.OK) {
2339 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2340 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2343 newComponentInstance.setOriginType(originType);
2347 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2349 if (eitherResourceName.isRight()) {
2350 resultOp = Either.right(eitherResourceName.right().value());
2354 origComponent = eitherResourceName.left().value();
2356 newComponentInstance.setName(resResourceInfo.getName());
2359 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2360 newComponentInstance.setPosX(resResourceInfo.getPosX());
2361 newComponentInstance.setPosY(resResourceInfo.getPosY());
2362 newComponentInstance.setDescription(resResourceInfo.getDescription());
2364 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2366 if (resultOp.isRight()) {
2367 log.debug("failed to create resource instance {}", resourceId);
2371 ComponentInstance updatedComponentInstance = resultOp.left().value();
2372 if (resultOp.isRight()) {
2373 log.debug("failed to create resource instance {}", resourceId);
2377 dataHolder.setCurrInstanceNode(origComponent);
2378 Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2379 if (mergeStatusEither.isRight()) {
2380 return Either.right(mergeStatusEither.right().value());
2383 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2384 if (postChangeVersionResult != ActionStatus.OK) {
2385 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2388 ComponentParametersView filter = new ComponentParametersView(true);
2389 filter.setIgnoreComponentInstances(false);
2390 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2391 if (updatedComponentRes.isRight()) {
2392 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2393 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2394 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2395 log.debug("Component with id {} was not found", containerComponentId);
2396 return Either.right(responseFormat);
2398 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2399 if (resourceInstanceStatus.isRight()) {
2400 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2403 resultOp = Either.left(resourceInstanceStatus.left().value());
2407 unlockComponent(resultOp, containerComponent);
2412 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2413 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2414 Component containerComponent = null;
2416 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2418 validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2420 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2421 if (validateComponentType.isRight()) {
2422 resultOp = Either.right(validateComponentType.right().value());
2426 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2427 if (validateContainerComponentExists.isRight()) {
2428 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2431 containerComponent = validateContainerComponentExists.left().value();
2433 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2434 if (resourceInstanceStatus.isRight()) {
2435 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2439 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2440 if (CollectionUtils.isEmpty(instanceProperties)) {
2441 instanceProperties = new ArrayList<>();
2443 resultOp = Either.left(instanceProperties);
2446 unlockComponent(resultOp, containerComponent);
2450 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2451 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2453 if (counterRes.isRight()) {
2454 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2455 StorageOperationStatus status = counterRes.right().value();
2456 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2457 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2459 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2465 * updates componentInstance modificationTime
2467 * @param componentInstance
2468 * @param componentInstanceType
2469 * @param modificationTime
2470 * @param inTransaction
2473 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2474 Either<ComponentInstanceData, ResponseFormat> result;
2475 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2477 if (updateComponentInstanceRes.isRight()) {
2478 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2479 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2481 result = Either.left(updateComponentInstanceRes.left().value());
2486 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2487 // TODO Add implementation
2488 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2492 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2493 // TODO Add implementation
2494 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2498 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2499 // TODO Add implementation
2500 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2504 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2505 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2508 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2510 Either<ComponentInstance, StorageOperationStatus> result = null;
2511 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2512 Optional<ComponentInstance> foundInstance = null;
2513 if (CollectionUtils.isEmpty(instances)) {
2514 result = Either.right(StorageOperationStatus.NOT_FOUND);
2516 if (result == null) {
2517 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2518 if (!foundInstance.isPresent()) {
2519 result = Either.right(StorageOperationStatus.NOT_FOUND);
2522 if (result == null) {
2523 result = Either.left(foundInstance.get());
2528 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2530 Long creationDate = origInstanceForUpdate.getCreationTime();
2532 Long modificationTime = System.currentTimeMillis();
2533 resourceInstanceForUpdate.setCreationTime(creationDate);
2534 resourceInstanceForUpdate.setModificationTime(modificationTime);
2536 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2538 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2539 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2542 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2544 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2545 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2547 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2548 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2550 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2551 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2553 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2554 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2556 if (resourceInstanceForUpdate.getOriginType() == null) {
2557 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2559 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2560 resourceInstanceForUpdate.setIsProxy(true);
2561 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2562 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2564 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2565 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2567 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2568 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2570 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2571 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2573 return resourceInstanceForUpdate;
2576 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2577 * @param containerComponentType
2578 * @param containerComponentId
2579 * @param componentInstanceUniqueId
2580 * @param capabilityType
2581 * @param capabilityName
2586 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2588 Component containerComponent = null;
2590 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2592 validateUserExists(userId, "Get Component Instance Properties By Id", false);
2593 if(resultOp == null){
2594 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2595 if (validateComponentType.isRight()) {
2596 resultOp = Either.right(validateComponentType.right().value());
2599 if(resultOp == null){
2600 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2601 if (validateContainerComponentExists.isRight()) {
2602 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2604 containerComponent = validateContainerComponentExists.left().value();
2607 if(resultOp == null){
2608 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2609 if (resourceInstanceStatus.isRight()) {
2610 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2612 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2617 unlockComponent(resultOp, containerComponent);
2621 private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2622 Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2623 CapabilityDefinition foundCapability;
2624 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2625 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2626 if (capabilitiesPerType != null) {
2627 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2628 if (capabilityOpt.isPresent()) {
2629 foundCapability = capabilityOpt.get();
2630 result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2634 if (result == null) {
2635 result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2640 private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2641 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2643 Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2644 if(getComponentInstanceCapabilityProperties != null) {
2645 if (getComponentInstanceCapabilityProperties.isRight()) {
2646 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2648 resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
2651 resultOp = Either.left(new ArrayList<>());
2653 } catch(Exception e){
2654 log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2655 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2660 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2661 String capabilityType, String capabilityName, String ownerId) {
2662 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2663 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2664 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2665 String capKey = sb.toString();
2667 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2668 .orElse(Collections.emptyMap());
2669 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2670 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2671 if (cap.isPresent()) {
2672 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2673 if (capProperties != null) {
2674 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2675 StorageOperationStatus status;
2676 if (instanceProperty.isPresent()) {
2677 instanceProperty.get().setValue(newValue);
2678 List<String> path = new ArrayList<>();
2679 path.add(componentInstanceUniqueId);
2681 instanceProperty.get().setPath(path);
2682 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2683 if (status != StorageOperationStatus.OK) {
2684 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2685 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2688 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2692 return componentsUtils.getResponseFormat(ActionStatus.OK);
2695 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2696 List<ComponentInstanceProperty> properties, String userId) {
2697 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2699 validateUserExists(userId, "update instance capability property", false);
2701 if (componentTypeEnum == null) {
2702 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2703 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2705 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2707 if (getResourceResult.isRight()) {
2708 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2709 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2711 Component containerComponent = getResourceResult.left().value();
2713 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2714 log.info("Restricted operation for user: {sourcePropList} on component {}", userId, containerComponentId);
2715 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2717 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2718 if (resourceInstanceStatus.isRight()) {
2719 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2721 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2723 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2724 if (lockStatus != StorageOperationStatus.OK) {
2725 log.debug("Failed to lock component {}", containerComponentId);
2726 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2729 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2730 if (allDataTypes.isRight()) {
2731 TitanOperationStatus status = allDataTypes.right().value();
2732 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2733 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2737 for (ComponentInstanceProperty property : properties) {
2738 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2739 newPropertyValueEither.bimap(updatedValue ->
2740 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2743 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2745 if (updateContainerRes.isRight()) {
2746 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2747 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2750 resultOp = Either.left(properties);
2754 if (resultOp == null || resultOp.isRight()) {
2755 titanDao.rollback();
2760 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2764 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2765 List<ComponentInstanceProperty> properties, String userId) {
2766 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2768 validateUserExists(userId, "update instance capability property", false);
2770 if (componentTypeEnum == null) {
2771 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2772 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2774 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2776 if (getResourceResult.isRight()) {
2777 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2778 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2780 Component containerComponent = getResourceResult.left().value();
2782 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2783 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2784 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2786 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2787 if (resourceInstanceStatus.isRight()) {
2788 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2790 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2792 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2793 if (lockStatus != StorageOperationStatus.OK) {
2794 log.debug("Failed to lock component {}", containerComponentId);
2795 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2799 for (ComponentInstanceProperty property : properties) {
2800 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2801 newPropertyValueEither.bimap(updatedValue ->
2802 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2805 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2807 if (updateContainerRes.isRight()) {
2808 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2809 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2812 resultOp = Either.left(properties);
2816 if (resultOp == null || resultOp.isRight()) {
2817 titanDao.rollback();
2822 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2826 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2827 String containerComponentId,
2828 String componentInstanceId,
2831 Map<String, ComponentInstance> resultMap = new HashMap<>();
2832 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2833 if (getOrigComponent.isRight()) {
2834 log.error("Failed to get the original component information");
2835 return Either.right(componentsUtils.getResponseFormat(
2836 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2839 Component origComponent = getOrigComponent.left().value();
2841 Either<Boolean, ResponseFormat> lockComponent = lockComponent(origComponent, "copyComponentInstance");
2842 if (lockComponent.isRight()) {
2843 log.error("destComponentInstance's data is {}", origComponent.toString());
2844 return Either.right(lockComponent.right().value());
2848 Either<ComponentInstance, ResponseFormat> actionResponse = null;
2850 actionResponse = createComponentInstance(
2851 "services", containerComponentId, userId, inputComponentInstance, true, false);
2853 if (actionResponse.isRight()) {
2854 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
2855 return Either.right(componentsUtils.getResponseFormat(
2856 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2861 // on failure of the create instance unlock the resource and rollback the transaction.
2862 if (null == actionResponse || actionResponse.isRight()) {
2863 titanDao.rollback();
2865 unlockComponent(actionResponse, origComponent);
2868 Either<String, ResponseFormat> resultOp = null;
2871 ComponentInstance destComponentInstance = actionResponse.left().value();
2872 log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2875 resultOp = deepCopyComponentInstance(
2876 origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2878 if (resultOp.isRight()) {
2879 log.error("Failed to deep copy component instance");
2880 return Either.right(componentsUtils.getResponseFormat(
2881 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2883 resultMap.put("componentInstance", destComponentInstance);
2884 return Either.left(resultMap);
2887 if (resultOp == null || resultOp.isRight()) {
2888 titanDao.rollback();
2892 log.debug("Success trasaction commit");
2895 unlockComponent(resultOp, origComponent);
2899 private Either<String, ResponseFormat> deepCopyComponentInstance(
2900 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2901 ComponentInstance destComponentInstance, String userId) {
2903 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2904 if (getDestComponent.isRight()) {
2905 log.error("Failed to get the dest component information");
2906 return Either.right(componentsUtils.getResponseFormat(
2907 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2910 Component destComponent = getDestComponent.left().value();
2912 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2913 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2914 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2915 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2916 return Either.right(componentsUtils.getResponseFormat(
2917 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2920 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2921 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2922 if (copyComponentInstanceWithAttributes.isRight()) {
2923 log.error("Failed to copy component instance with attributes as part of deep copy");
2924 return Either.right(componentsUtils.getResponseFormat(
2925 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2927 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2930 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2931 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2932 ComponentInstance destComponentInstance, String userId) {
2933 log.debug("start to copy ComponentInstance with properties and inputs");
2935 List<ComponentInstanceProperty> sourcePropList = null;
2936 if (sourceComponent.getComponentInstancesProperties() != null
2937 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2938 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2939 log.debug("sourcePropList");
2942 List<ComponentInstanceProperty> destPropList = null;
2943 String destComponentInstanceId = destComponentInstance.getUniqueId();
2944 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2945 if (destComponent.getComponentInstancesProperties() != null
2946 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2947 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2948 log.debug("destPropList {}");
2951 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2953 if (null != destPropList && null != sourcePropList) {
2954 log.debug("start to set property and attribute");
2955 for (ComponentInstanceProperty destProp : destPropList) {
2956 String destPropertyName = destProp.getName();
2957 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2958 if (!destPropertyName.equals(sourceProp.getName())) {
2961 log.debug("now set property");
2962 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2963 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2964 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2966 destProp.setValue(sourceProp.getValue());
2967 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2968 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2969 if (updatePropertyValueEither.isRight()) {
2970 log.error("Failed to copy the property {}", destPropertyName);
2971 return Either.right(componentsUtils.getResponseFormat(
2972 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2977 log.debug("Now start to update inputs");
2979 if (sourceProp.getGetInputValues() != null) {
2980 if (sourceProp.getGetInputValues().isEmpty()) {
2981 log.debug("source property input values empty");
2984 log.debug("Now starting to copy the {} property", destPropertyName);
2986 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2987 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2988 if (getSourceInputDefaultValue.isRight()) {
2989 return Either.right(getSourceInputDefaultValue.right().value());
2991 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2996 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2999 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
3000 Component destComponent,
3001 String sourceComponentInstanceId,
3002 ComponentInstance destComponentInstance,
3004 String destComponentInstanceId = destComponentInstance.getUniqueId();
3006 log.info("start to copy component instance with attributes");
3008 List<ComponentInstanceProperty> sourceAttributeList = null;
3009 if (sourceComponent.getComponentInstancesAttributes() != null
3010 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
3011 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
3012 log.info("sourceAttributes {}");
3015 List<ComponentInstanceProperty> destAttributeList = null;
3016 if (destComponent.getComponentInstancesAttributes() != null
3017 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
3018 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
3019 log.info("destAttributeList {}");
3021 if (null != sourceAttributeList && null != destAttributeList) {
3022 log.info("set attribute");
3024 for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
3025 String sourceAttributeName = sourceAttribute.getName();
3026 for (ComponentInstanceProperty destAttribute : destAttributeList) {
3027 if (sourceAttributeName.equals(destAttribute.getName())) {
3028 if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
3029 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
3031 sourceAttribute.setUniqueId(
3032 UniqueIdBuilder.buildResourceInstanceUniuqeId(
3033 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
3035 Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
3036 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
3037 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
3039 if (updateAttributeValueEither.isRight()) {
3040 log.error("Failed to copy the attribute");
3041 return Either.right(componentsUtils
3042 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3043 "Failed to paste component instance to the canvas, attribute copy"));
3052 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3055 private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
3057 String resourceInstanceId,
3058 ComponentInstanceProperty attribute,
3061 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
3063 validateUserExists(userId, "Create or Update attribute value", false);
3065 if (componentTypeEnum == null) {
3066 BeEcompErrorManager.getInstance().logInvalidInputError(
3067 "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3068 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3072 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3074 if (getResourceResult.isRight()) {
3075 log.info("Failed to retrieve component id {}", componentId);
3076 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3080 Component containerComponent = getResourceResult.left().value();
3082 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3084 if (resourceInstanceStatus.isRight()) {
3085 resultOp = Either.right(componentsUtils.getResponseFormat(
3086 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3090 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3093 String propertyType = attribute.getType();
3094 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3095 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3097 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3098 SchemaDefinition def = attribute.getSchema();
3100 log.info("Schema doesn't exists for attribute of type {}", type);
3101 return Either.right(componentsUtils.getResponseFormat(
3102 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3104 PropertyDataDefinition propDef = def.getProperty();
3105 if (propDef == null) {
3106 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3107 return Either.right(componentsUtils.getResponseFormat(
3108 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3112 List<ComponentInstanceProperty> instanceAttributes = containerComponent.
3113 getComponentInstancesAttributes().get(resourceInstanceId);
3114 Optional<ComponentInstanceProperty> instanceAttribute =
3115 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3116 StorageOperationStatus status;
3118 if (instanceAttribute.isPresent()) {
3119 log.info("updateComponentInstanceAttribute");
3120 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3122 log.info("addComponentInstanceAttribute");
3123 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3125 if (status != StorageOperationStatus.OK) {
3126 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3127 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3130 List<String> path = new ArrayList<>();
3131 path.add(foundResourceInstance.getUniqueId());
3132 attribute.setPath(path);
3134 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3135 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3136 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3138 if (updateContainerRes.isRight()) {
3139 ActionStatus actionStatus = componentsUtils.
3140 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3141 resultOp = Either.right(componentsUtils.
3142 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3145 resultOp = Either.left(attribute);
3152 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3153 String componentInstanceId,
3154 ComponentInstanceProperty property) {
3155 Either<String, ResponseFormat> resultOp;
3156 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3158 if (getComponent.isRight()) {
3159 log.error("Failed to get the component information");
3160 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3161 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3164 Component containerComponent = getComponent.left().value();
3166 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3167 containerComponent, componentInstanceId, property);
3168 if (status != StorageOperationStatus.OK) {
3169 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3170 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3174 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3175 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3177 if (updateContainerRes.isRight()) {
3178 ActionStatus actionStatus = componentsUtils.
3179 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3180 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3184 return Either.left("Update OK");
3187 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3188 List<InputDefinition> inputList = component.getInputs();
3189 for (InputDefinition input : inputList) {
3190 if (input.getUniqueId().equals(inputId)) {
3191 if (input.getDefaultValue() == null) {
3192 log.debug("The input's default value is null");
3193 return Either.left(null);
3195 return Either.left(input.getDefaultValue());
3198 log.error("The input's default value with id {} is not found", inputId);
3199 return Either.right(componentsUtils.getResponseFormat(
3200 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3204 * Method to delete selected nodes and edges on composition page
3205 * @param containerComponentType
3206 * @param componentId
3207 * @param componentInstanceIdList
3211 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3213 List<String> componentInstanceIdList,
3216 List<String> deleteErrorIds = new ArrayList<>();
3217 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3218 Either<Component, ResponseFormat> validateResponse = validateUser(containerComponentType, componentId, userId);
3219 if (validateResponse.isRight()) {
3220 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3221 return deleteErrorMap;
3223 Component containerComponent = validateResponse.left().value();
3225 Either<Boolean, ResponseFormat> lockComponent = lockComponent(
3226 containerComponent, "batchDeleteComponentInstance");
3227 if (lockComponent.isRight()) {
3228 log.error("Failed to lockComponent containerComponent");
3229 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3230 return deleteErrorMap;
3234 for (String eachInstanceId : componentInstanceIdList) {
3235 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3236 containerComponent, containerComponentType, componentId, eachInstanceId);
3237 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3238 if (actionResponse.isRight()) {
3239 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3240 deleteErrorIds.add(eachInstanceId);
3243 //sending the ids of the error nodes that were not deleted to UI
3244 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3245 return deleteErrorMap;
3247 unlockComponent(validateResponse, containerComponent);
3251 private Either<Component, ResponseFormat> validateUser(String containerComponentParam,
3252 String containerComponentId,
3254 validateUserExists(userId, "delete Component Instance", false);
3255 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
3256 if (validateComponentType.isRight()) {
3257 log.error("ComponentType[{}] doesn't support", containerComponentParam);
3258 return Either.right(validateComponentType.right().value());
3261 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
3262 Either<Component, ResponseFormat> validateComponentExists = validateComponentExists(
3263 containerComponentId, containerComponentType, null);
3264 if (validateComponentExists.isRight()) {
3265 log.error("Component Id[{}] doesn't exist", containerComponentId);
3266 return Either.right(validateComponentExists.right().value());
3269 Component containerComponent = validateComponentExists.left().value();
3270 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
3271 if (validateCanWorkOnComponent.isRight()) {
3272 return Either.right(validateCanWorkOnComponent.right().value());
3274 return Either.left(containerComponent);
3277 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3278 String containerComponentType,
3279 String containerComponentId,
3280 String componentInstanceId) {
3282 Either<ComponentInstance, ResponseFormat> resultOp;
3283 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3285 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3287 if (resultOp.isRight()) {
3288 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3289 return Either.right(resultOp.right().value());
3292 log.info("Successfully deleted instance with id {}", componentInstanceId);
3293 return Either.left(resultOp.left().value());