re base code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ComponentInstanceBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.be.components.impl;
22
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.merge.instance.ComponentInstanceMergeDataBusinessLogic;
31 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
32 import org.openecomp.sdc.be.components.validation.ComponentValidations;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
37 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
38 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
39 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
41 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
48 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
49 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
50 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
51 import org.openecomp.sdc.be.model.ArtifactDefinition;
52 import org.openecomp.sdc.be.model.CapabilityDefinition;
53 import org.openecomp.sdc.be.model.Component;
54 import org.openecomp.sdc.be.model.ComponentInstance;
55 import org.openecomp.sdc.be.model.ComponentInstanceInput;
56 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
57 import org.openecomp.sdc.be.model.ComponentParametersView;
58 import org.openecomp.sdc.be.model.DataTypeDefinition;
59 import org.openecomp.sdc.be.model.GroupDefinition;
60 import org.openecomp.sdc.be.model.InputDefinition;
61 import org.openecomp.sdc.be.model.LifecycleStateEnum;
62 import org.openecomp.sdc.be.model.PropertyDefinition;
63 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
64 import org.openecomp.sdc.be.model.RelationshipInfo;
65 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
66 import org.openecomp.sdc.be.model.RequirementDefinition;
67 import org.openecomp.sdc.be.model.Resource;
68 import org.openecomp.sdc.be.model.Service;
69 import org.openecomp.sdc.be.model.User;
70 import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
71 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
72 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
73 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
74 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
75 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
76 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
77 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
78 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
79 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
80 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
81 import org.openecomp.sdc.common.api.Constants;
82 import org.openecomp.sdc.common.datastructure.Wrapper;
83 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
84 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
85 import org.openecomp.sdc.common.log.wrappers.Logger;
86 import org.openecomp.sdc.common.util.ValidationUtils;
87 import org.openecomp.sdc.exception.ResponseFormat;
88 import org.springframework.beans.factory.annotation.Autowired;
89
90 import java.util.ArrayList;
91 import java.util.Collection;
92 import java.util.Collections;
93 import java.util.HashMap;
94 import java.util.Iterator;
95 import java.util.List;
96 import java.util.Map;
97 import java.util.Map.Entry;
98 import java.util.Objects;
99 import java.util.Optional;
100 import java.util.Set;
101 import java.util.UUID;
102 import java.util.function.BiConsumer;
103 import java.util.stream.Collectors;
104
105 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
106
107 @org.springframework.stereotype.Component
108 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
109
110     private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
111     private static final String VF_MODULE = "org.openecomp.groups.VfModule";
112     public static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
113     public static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
114     public static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
115     public static final String INVALID_COMPONENT_TYPE = "invalid component type";
116     public static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
117     public static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
118     public static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
119
120     @Autowired
121     private IComponentInstanceOperation componentInstanceOperation;
122
123     @Autowired
124     private ArtifactsBusinessLogic artifactBusinessLogic;
125
126     @Autowired
127     private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
128
129     @Autowired
130     private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
131
132     @Autowired
133     private ForwardingPathOperation forwardingPathOperation;
134
135
136     public ComponentInstanceBusinessLogic() {
137     }
138
139     public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
140         return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
141     }
142
143     public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
144         List<ComponentInstanceProperty> resList = new ArrayList<>();
145         Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
146         if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
147             ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
148                 @Override
149                 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
150                     String ciName = "";
151                     Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
152                     if(ciOp.isPresent())
153                         ciName = ciOp.get().getName();
154                     if (ciPropList != null && !ciPropList.isEmpty()) {
155                         for(ComponentInstanceProperty prop: ciPropList){
156                             List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
157                             if(inputsValues != null && !inputsValues.isEmpty()){
158                                 for(GetInputValueDataDefinition inputData: inputsValues){
159                                     if(isGetInputValueForInput(inputData, inputId)){
160                                         prop.setComponentInstanceId(s);
161                                         prop.setComponentInstanceName(ciName);
162                                         resList.add(prop);
163                                         break;
164                                     }
165                                 }
166                             }
167
168                         }
169                     }
170                 }
171             });
172         }
173         return resList;
174
175     }
176
177     public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
178         List<ComponentInstanceInput> resList = new ArrayList<>();
179         Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
180         if(ciInputsMap != null && !ciInputsMap.isEmpty()){
181             ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
182                 @Override
183                 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
184                     String ciName = "";
185                     Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
186                     if(ciOp.isPresent())
187                         ciName = ciOp.get().getName();
188                     if (ciPropList != null && !ciPropList.isEmpty()) {
189                         for(ComponentInstanceInput prop: ciPropList){
190                             List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
191                             if(inputsValues != null && !inputsValues.isEmpty()){
192                                 for(GetInputValueDataDefinition inputData: inputsValues){
193                                     if(isGetInputValueForInput(inputData, inputId)){
194                                         prop.setComponentInstanceId(s);
195                                         prop.setComponentInstanceName(ciName);
196                                         resList.add(prop);
197                                         break;
198                                     }
199                                 }
200                             }
201
202                         }
203                     }
204                 }
205             });
206         }
207         return resList;
208
209     }
210
211     public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
212
213         Component origComponent = null;
214         Either<ComponentInstance, ResponseFormat> resultOp = null;
215         User user = null;
216         org.openecomp.sdc.be.model.Component containerComponent = null;
217         ComponentTypeEnum containerComponentType;
218
219         try {
220             user = validateUserExists(userId, "create Component Instance", inTransaction);
221
222             Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
223             if (validateValidJson.isRight()) {
224                 return Either.right(validateValidJson.right().value());
225             }
226
227             Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
228             if (validateComponentType.isRight()) {
229                 return Either.right(validateComponentType.right().value());
230             } else {
231                 containerComponentType = validateComponentType.left().value();
232             }
233
234             Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
235             if (validateComponentExists.isRight()) {
236                 return Either.right(validateComponentExists.right().value());
237             } else {
238                 containerComponent = validateComponentExists.left().value();
239             }
240
241             if (ModelConverter.isAtomicComponent(containerComponent)) {
242                 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
243                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
244             }
245
246             Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
247             if (validateCanWorkOnComponent.isRight()) {
248                 return Either.right(validateCanWorkOnComponent.right().value());
249             }
250
251             if (resourceInstance != null && containerComponentType != null) {
252                 OriginTypeEnum originType = resourceInstance.getOriginType();
253                 if (originType == OriginTypeEnum.ServiceProxy) {
254                     Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
255                     if (serviceProxyOrigin.isRight()) {
256                         log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
257                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
258                     }
259                     origComponent = serviceProxyOrigin.left().value();
260
261                     StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
262                     if (fillProxyRes != StorageOperationStatus.OK) {
263                         log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
264                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
265
266                     }
267
268                 } else {
269                     Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
270
271                     if (getOriginComponentRes.isRight()) {
272                         return Either.right(getOriginComponentRes.right().value());
273                     } else {
274                         origComponent = getOriginComponentRes.left().value();
275                     }
276                 }
277             }
278             if (needLock) {
279                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
280                 if (lockComponent.isRight()) {
281                     return Either.right(lockComponent.right().value());
282                 }
283             }
284             log.debug("Try to create entry on graph");
285             resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
286             return resultOp;
287
288         } finally {
289             if (needLock)
290                 unlockComponent(resultOp, containerComponent);
291         }
292     }
293
294     private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
295         resourceInstance.setIsProxy(true);
296         ComponentParametersView filter = new ComponentParametersView(true);
297         filter.setIgnoreCapabilities(false);
298         filter.setIgnoreCapabiltyProperties(false);
299         filter.setIgnoreComponentInstances(false);
300         filter.setIgnoreRequirements(false);
301         Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
302         if (serviceRes.isRight()) {
303             return serviceRes.right().value();
304         }
305         Component service = serviceRes.left().value();
306         Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
307         resourceInstance.setCapabilities(capabilities);
308         Map<String, List<RequirementDefinition>> req = service.getRequirements();
309         resourceInstance.setRequirements(req);
310
311         String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
312         String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
313         int lastIndexOf = toscaResourceName.lastIndexOf('.');
314         if (lastIndexOf != -1) {
315             String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
316             resourceInstance.setToscaComponentName(proxyToscaName);
317         }
318         resourceInstance.setName(name);
319         resourceInstance.setIsProxy(true);
320         resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
321         resourceInstance.setSourceModelName(service.getName());
322         resourceInstance.setSourceModelUuid(service.getUUID());
323         resourceInstance.setSourceModelUid(service.getUniqueId());
324         resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
325         resourceInstance.setDescription("A Proxy for Service " + service.getName());
326         resourceInstance.setComponentVersion(service.getVersion());
327
328         return StorageOperationStatus.OK;
329     }
330
331     public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
332
333         Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
334         ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
335         RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
336
337         User user = validateUserExists(userId, "create And Associate RI To RI", false);
338
339         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
340         if (validateComponentType.isRight()) {
341             return Either.right(validateComponentType.right().value());
342         }
343
344         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
345
346         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
347         if (validateComponentExists.isRight()) {
348             return Either.right(validateComponentExists.right().value());
349         }
350         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
351
352         if (ModelConverter.isAtomicComponent(containerComponent)) {
353             log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
354             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
355         }
356
357         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
358         if (validateCanWorkOnComponent.isRight()) {
359             return Either.right(validateCanWorkOnComponent.right().value());
360         }
361
362         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
363         if (lockComponent.isRight()) {
364             return Either.right(lockComponent.right().value());
365         }
366
367         try {
368             log.debug("Try to create entry on graph");
369             Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
370
371             if (eitherResourceName.isRight()) {
372                 resultOp = Either.right(eitherResourceName.right().value());
373                 return resultOp;
374             }
375             Component origComponent = eitherResourceName.left().value();
376
377             Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
378             if (result.isRight()) {
379                 log.debug("Failed to create resource instance {}", containerComponentId);
380                 resultOp = Either.right(result.right().value());
381                 return resultOp;
382
383             }
384
385             log.debug("Entity on graph is created.");
386             ComponentInstance resResourceInfo = result.left().value();
387             if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
388                 associationInfo.setFromNode(resResourceInfo.getUniqueId());
389             } else {
390                 associationInfo.setToNode(resResourceInfo.getUniqueId());
391             }
392
393             RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
394             Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
395             if (resultReqCapDef.isLeft()) {
396                 log.debug("Enty on graph is created.");
397                 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
398                 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
399                 resultOp = Either.left(resInfo);
400                 return resultOp;
401
402             } else {
403                 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
404                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
405                 return resultOp;
406             }
407
408         } finally {
409             unlockComponent(resultOp, containerComponent);
410         }
411     }
412
413     private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
414         return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
415     }
416
417     private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
418         return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
419     }
420
421     private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
422         Either<Component, ResponseFormat> eitherResponse;
423         Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
424         if (eitherComponent.isRight()) {
425             log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
426             eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
427         } else {
428             eitherResponse = Either.left(eitherComponent.left().value());
429         }
430         return eitherResponse;
431     }
432
433     private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
434         Either<ComponentInstance, ResponseFormat> resultOp;
435
436         Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
437
438         if (result.isRight()) {
439             log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
440             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
441             return resultOp;
442         }
443
444         log.debug("Entity on graph is created.");
445         Component updatedComponent = result.left().value().getLeft();
446         Map<String, String> existingEnvVersions = new HashMap<>();
447         // TODO existingEnvVersions ??
448         Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
449         if (addComponentInstanceArtifacts.isRight()) {
450             log.debug("Failed to create component instance {}", componentInstance.getName());
451             resultOp = Either.right(addComponentInstanceArtifacts.right().value());
452             return resultOp;
453         }
454
455         Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
456         if (!updatedInstanceOptional.isPresent()) {
457             log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
458             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
459             return resultOp;
460         }
461         resultOp = Either.left(updatedInstanceOptional.get());
462         return resultOp;
463     }
464
465 /**
466  * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
467  * @param containerComponent
468  * @param componentInstance
469  * @param originComponent
470  * @param user
471  * @param existingEnvVersions
472  * @return
473  */
474     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) {
475
476         log.debug("add artifacts to resource instance");
477         List<GroupDefinition> filteredGroups = null;
478         ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
479         if (!ActionStatus.OK.equals(status)) {
480             ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
481             return Either.right(resultOp);
482         }
483         StorageOperationStatus artStatus;
484         // generate heat_env if necessary
485         Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
486         if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
487
488             Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
489             Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
490
491             for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
492                 String type = artifact.getArtifactType();
493                 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
494                     finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
495                 }
496                 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
497                     continue;
498                 }
499                 if (artifact.checkEsIdExist()) {
500                     Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
501                             componentInstance.getName(), user, containerComponent, existingEnvVersions);
502                     if (createHeatEnvPlaceHolder.isRight()) {
503                         return Either.right(createHeatEnvPlaceHolder.right().value());
504                     }
505                     ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
506                     // put env
507                     finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
508
509                     if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
510                         filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
511                     }
512                     if (CollectionUtils.isNotEmpty(filteredGroups)) {
513                         for (GroupDefinition groupInstance : filteredGroups) {
514                             Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
515                             if (op.isPresent()) {
516                                 List<ArtifactDefinition> artifactsUid;
517                                 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
518                                     artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
519                                 } else {
520                                     artifactsUid = new ArrayList<>();
521                                 }
522                                 artifactsUid.add(artifactDefinition);
523                                 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
524                                 break;
525                             }
526                         }
527                     }
528                 }
529             }
530             artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
531             if (artStatus != StorageOperationStatus.OK) {
532                 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
533                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
534
535             }
536             StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
537             if (result != StorageOperationStatus.OK) {
538                 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
539                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
540             }
541             componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
542         }
543
544         artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
545         if (artStatus != StorageOperationStatus.OK) {
546             log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
547             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
548
549         }
550         componentInstance.setArtifacts(originComponent.getArtifacts());
551         return Either.left(ActionStatus.OK);
552     }
553
554     private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
555         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
556
557         Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
558         if (getResourceDeploymentArtifacts.isRight()) {
559             StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
560             if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
561                 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
562                 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
563             }
564         } else {
565             deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
566         }
567
568         if (!deploymentArtifacts.isEmpty()) {
569             Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
570             for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
571                 if (!artifact.getValue().checkEsIdExist()) {
572                     tempDeploymentArtifacts.remove(artifact.getKey());
573                 }
574             }
575
576             resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
577         }
578
579         return ActionStatus.OK;
580     }
581
582     public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
583         return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
584     }
585
586     public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
587             boolean needLock, boolean createNewTransaction) {
588
589         validateUserExists(userId, "update Component Instance", inTransaction);
590
591         Either<ComponentInstance, ResponseFormat> resultOp = null;
592
593         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
594         if (validateComponentType.isRight()) {
595             return Either.right(validateComponentType.right().value());
596         }
597
598         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
599
600         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
601         if (validateComponentExists.isRight()) {
602             return Either.right(validateComponentExists.right().value());
603         }
604         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
605
606         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
607         if (validateCanWorkOnComponent.isRight()) {
608             return Either.right(validateCanWorkOnComponent.right().value());
609         }
610         ComponentTypeEnum instanceType = getComponentType(containerComponentType);
611         Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
612         if (validateParentStatus.isRight()) {
613             log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
614             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
615             return resultOp;
616         }
617         if (!validateParentStatus.left().value()) {
618             resultOp = Either.right(
619                     componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
620             return resultOp;
621         }
622
623         if (needLock) {
624             Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
625             if (lockComponent.isRight()) {
626                 return Either.right(lockComponent.right().value());
627             }
628         }
629         try {
630
631             Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
632
633             if (eitherResourceName.isRight()) {
634                 resultOp = Either.right(eitherResourceName.right().value());
635                 return resultOp;
636             }
637             Component origComponent = eitherResourceName.left().value();
638
639             resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
640             return resultOp;
641
642         } finally {
643             if (needLock)
644                 unlockComponent(resultOp, containerComponent);
645         }
646     }
647
648     // New Multiple Instance Update API
649     public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
650
651         Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
652         org.openecomp.sdc.be.model.Component containerComponent = null;
653         try {
654             validateUserExists(userId, "update Component Instance", true);
655
656             Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
657             if (validateComponentType.isRight()) {
658                 return Either.right(validateComponentType.right().value());
659             }
660
661             final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
662
663             ComponentParametersView componentFilter = new ComponentParametersView();
664             componentFilter.disableAll();
665             componentFilter.setIgnoreUsers(false);
666             componentFilter.setIgnoreComponentInstances(false);
667             Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
668             if (validateComponentExists.isRight()) {
669                 return Either.right(validateComponentExists.right().value());
670             }
671
672             containerComponent = validateComponentExists.left().value();
673
674             Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
675             if (validateCanWorkOnComponent.isRight()) {
676                 return Either.right(validateCanWorkOnComponent.right().value());
677             }
678
679             ComponentTypeEnum instanceType = getComponentType(containerComponentType);
680
681             for (ComponentInstance componentInstance : componentInstanceList) {
682                 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
683                 if (!validateParent) {
684                     resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
685                         containerComponentId));
686                     return resultOp;
687                 }
688             }
689
690             if (needLock) {
691
692                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
693                 if (lockComponent.isRight()) {
694                     return Either.right(lockComponent.right().value());
695                 }
696             }
697
698             List<ComponentInstance> updatedList = new ArrayList<>();
699             List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
700             List<ComponentInstance> listForUpdate = new ArrayList<>();
701             if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
702                 containerComponent.setComponentInstances(componentInstanceList);
703             else {
704                 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
705                 while (iterator.hasNext()) {
706                     ComponentInstance origInst = iterator.next();
707                     Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
708                     if (op.isPresent()) {
709                         ComponentInstance updatedCi = op.get();
710                         updatedCi = buildComponentInstance(updatedCi, origInst);
711
712                         Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
713                         if (!isUniqueName) {
714                             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());
715                             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
716                             return resultOp;
717                         }
718
719                         listForUpdate.add(updatedCi);
720                     } else
721                         listForUpdate.add(origInst);
722                 }
723                 containerComponent.setComponentInstances(listForUpdate);
724
725                 if (resultOp == null) {
726                     Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
727                     if (updateStatus.isRight()) {
728                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
729                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
730                         return resultOp;
731                     }
732                     for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
733                         Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
734                         if (op.isPresent()) {
735                             updatedList.add(updatedInstance);
736                         }
737                     }
738                 }
739             }
740
741             resultOp = Either.left(updatedList);
742             return resultOp;
743
744         } finally {
745             if (needLock) {
746                 unlockComponent(resultOp, containerComponent);
747             }
748         }
749     }
750
751     private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
752         return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
753     }
754
755     private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
756         if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
757             return ComponentTypeEnum.SERVICE_INSTANCE;
758         } else {
759             return ComponentTypeEnum.RESOURCE_INSTANCE;
760         }
761     }
762
763     private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
764             ComponentInstance componentInstance) {
765
766         Either<ComponentInstance, ResponseFormat> resultOp = null;
767         Optional<ComponentInstance> componentInstanceOptional = null;
768         Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
769         ComponentInstance oldComponentInstance = null;
770         boolean isNameChanged = false;
771
772         if (resultOp == null) {
773             componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
774             if (!componentInstanceOptional.isPresent()) {
775                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
776                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
777             }
778         }
779         if (resultOp == null) {
780             oldComponentInstance = componentInstanceOptional.get();
781             String newInstanceName = componentInstance.getName();
782             if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
783                 isNameChanged = true;
784             Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
785             if (!isUniqueName) {
786                 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);
787                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
788             }
789         }
790         if (resultOp == null) {
791             updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
792             if (updateRes.isRight()) {
793                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
794                         updateRes.right().value());
795                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
796             } else {
797                 // region - Update instance Groups
798                 if (isNameChanged) {
799                     Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
800                     if (result.isRight())
801                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
802                 }
803                 // endregion
804             }
805         }
806         if (resultOp == null) {
807             String newInstanceId = updateRes.left().value().getRight();
808             Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
809
810             if (!updatedInstanceOptional.isPresent()) {
811                 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
812                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
813             } else {
814                 resultOp = Either.left(updatedInstanceOptional.get());
815             }
816
817         }
818         if (resultOp == null) {
819             resultOp = Either.left(componentInstanceOptional.get());
820         }
821         return resultOp;
822     }
823
824     /**
825      * @param oldPrefix-
826      *            The normalized old vf name
827      * @param newNormailzedPrefix-
828      *            The normalized new vf name
829      * @param qualifiedGroupInstanceName-
830      *            old Group Instance Name
831      **/
832     // modify group names
833     private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
834         if (qualifiedGroupInstanceName == null) {
835             log.info("CANNOT change group name ");
836             return null;
837         }
838         if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
839             return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
840         return qualifiedGroupInstanceName;
841     }
842
843     private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
844         oldComponentInstance.setName(newComponentInstance.getName());
845         oldComponentInstance.setModificationTime(System.currentTimeMillis());
846         oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
847         if (oldComponentInstance.getGroupInstances() != null)
848             oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
849         return oldComponentInstance;
850     }
851
852     public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
853
854         validateUserExists(userId, "delete Component Instance", false);
855
856         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
857         if (validateComponentType.isRight()) {
858             return Either.right(validateComponentType.right().value());
859         }
860
861         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
862         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
863         if (validateComponentExists.isRight()) {
864             return Either.right(validateComponentExists.right().value());
865         }
866         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
867         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
868         if (validateCanWorkOnComponent.isRight()) {
869             return Either.right(validateCanWorkOnComponent.right().value());
870         }
871
872         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
873         if (lockComponent.isRight()) {
874             return Either.right(lockComponent.right().value());
875         }
876
877         Either<ComponentInstance, ResponseFormat> resultOp = null;
878         try {
879             resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
880             if (resultOp.isRight()){
881                 return resultOp;
882             }
883             Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
884                 containerComponentType, resultOp);
885             if (deleteEither.isRight()){
886                 return deleteEither;
887             }
888             return deleteEither;
889
890         } finally {
891             unlockComponent(resultOp, containerComponent);
892         }
893     }
894
895     public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
896             Either<ComponentInstance, ResponseFormat> resultOp) {
897         if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
898             final ComponentInstance componentInstance = resultOp.left().value();
899             List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
900             if (!pathIDsToBeDeleted.isEmpty()) {
901                 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
902                         pathIDsToBeDeleted);
903                 if(deleteForwardingPathsEither.isRight()) {
904                     resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
905                 }
906
907             }
908         }
909         return resultOp;
910     }
911
912
913     private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId,  List<String> pathIdsToDelete){
914
915         Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
916         if(storageStatus.isRight()) {
917             return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
918         }
919         Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
920             Sets.newHashSet(pathIdsToDelete));
921
922         if(result.isRight()) {
923             return Either.right(componentsUtils.getResponseFormat(result.right().value()));
924         }
925         return  Either.left(result.left().value());
926     }
927
928     private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
929         ComponentParametersView filter = new ComponentParametersView(true);
930         filter.setIgnoreForwardingPath(false);
931         Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
932                 .getToscaElement(containerComponentId, filter);
933         Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
934         List<String> pathIDsToBeDeleted = new ArrayList<>();
935
936         allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
937                 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
938
939         return pathIDsToBeDeleted;
940     }
941
942     private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
943                                              String componentInstanceId){
944         return pathDataDefinition.getPathElements().getListToscaDataDefinition()
945                 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
946                         elementDataDefinition.getToNode()
947                  .equalsIgnoreCase(componentInstanceId));
948     }
949
950
951     private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
952
953         Either<ComponentInstance, ResponseFormat> resultOp = null;
954         ComponentInstance deletedInstance = null;
955         Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
956
957         if (deleteRes.isRight()) {
958             log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
959             ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
960             resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
961         }
962         if (resultOp == null) {
963             log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
964             deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
965             resultOp = Either.left(deletedInstance);
966         }
967         if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
968             List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
969             for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
970                 Map<String, String> members = currGroup.getMembers();
971                 if (members != null && members.containsKey(deletedInstance.getName())) {
972                     members.remove(deletedInstance.getName());
973                     groupsToUpdate.add(currGroup);
974                 }
975             }
976             Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
977             if (updateGroupsRes.isRight()) {
978                 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
979                 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
980                 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
981             }
982         }
983         if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
984             List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
985             if (CollectionUtils.isNotEmpty(inputsToDelete)) {
986                 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
987                 if (deleteInputsRes != StorageOperationStatus.OK) {
988                     log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
989                     resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
990                 }
991             }
992         }
993         return resultOp;
994     }
995
996     private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
997         ComponentInstance foundInstance = null;
998         for (ComponentInstance instance : containerComponent.getComponentInstances()) {
999             if (instance.getUniqueId().equals(componentInstanceId)) {
1000                 foundInstance = instance;
1001                 containerComponent.getComponentInstances().remove(instance);
1002                 break;
1003             }
1004         }
1005         findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1006         return foundInstance;
1007     }
1008
1009     private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1010         if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1011             containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1012         }
1013     }
1014
1015     private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1016         return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1017     }
1018
1019     public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1020         return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1021     }
1022
1023     public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1024         boolean createNewTransaction) {
1025
1026         validateUserExists(userId, "associate Ri To RI", inTransaction);
1027
1028         Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1029
1030         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1031         if (validateComponentExists.isRight()) {
1032             return Either.right(validateComponentExists.right().value());
1033         }
1034         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1035
1036         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1037         if (validateCanWorkOnComponent.isRight()) {
1038             return Either.right(validateCanWorkOnComponent.right().value());
1039         }
1040         if (needLock) {
1041             Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1042
1043             if (lockComponent.isRight()) {
1044                 return Either.right(lockComponent.right().value());
1045             }
1046         }
1047
1048         try {
1049
1050             resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1051
1052             return resultOp;
1053
1054         } finally {
1055             if (needLock)
1056                 unlockComponent(resultOp, containerComponent);
1057         }
1058     }
1059
1060     public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1061
1062         log.debug("Try to create entry on graph");
1063         Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1064
1065         Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1066
1067         if (result.isLeft()) {
1068             log.debug("Enty on graph is created.");
1069             RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1070             resultOp = Either.left(requirementCapabilityRelDef);
1071             return resultOp;
1072
1073         } else {
1074             log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1075             String fromNameOrId = "";
1076             String toNameOrId = "";
1077             Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1078             Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1079
1080             toNameOrId = requirementDef.getFromNode();
1081             fromNameOrId = requirementDef.getFromNode();
1082             if (fromResult.isLeft()) {
1083                 fromNameOrId = fromResult.left().value().getName();
1084             }
1085             if (toResult.isLeft()) {
1086                 toNameOrId = toResult.left().value().getName();
1087             }
1088
1089             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1090
1091             return resultOp;
1092         }
1093
1094     }
1095
1096     public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1097         validateUserExists(userId, "dissociate RI From RI", false);
1098
1099         Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1100         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1101         if (validateComponentExists.isRight()) {
1102             return Either.right(validateComponentExists.right().value());
1103         }
1104         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1105
1106         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1107         if (validateCanWorkOnComponent.isRight()) {
1108             return Either.right(validateCanWorkOnComponent.right().value());
1109         }
1110         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1111
1112         if (lockComponent.isRight()) {
1113             return Either.right(lockComponent.right().value());
1114         }
1115         try {
1116             log.debug("Try to create entry on graph");
1117             Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1118             if (result.isLeft()) {
1119                 log.debug("Enty on graph is created.");
1120                 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1121                 resultOp = Either.left(requirementCapabilityRelDef);
1122                 return resultOp;
1123
1124             } else {
1125
1126                 log.debug("Failed to dissocaite node  {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1127                 String fromNameOrId = "";
1128                 String toNameOrId = "";
1129                 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1130                 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1131
1132                 toNameOrId = requirementDef.getFromNode();
1133                 fromNameOrId = requirementDef.getFromNode();
1134                 if (fromResult.isLeft()) {
1135                     fromNameOrId = fromResult.left().value().getName();
1136                 }
1137                 if (toResult.isLeft()) {
1138                     toNameOrId = toResult.left().value().getName();
1139                 }
1140
1141                 resultOp = Either
1142                         .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1143                 return resultOp;
1144             }
1145         } finally {
1146             unlockComponent(resultOp, containerComponent);
1147         }
1148     }
1149     /**
1150      * Allows to get relation contained in specified component according to received Id
1151      * @param componentId
1152      * @param relationId
1153      * @param userId
1154      * @param componentTypeEnum
1155      * @return
1156      */
1157     public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1158
1159         Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1160         try {
1161             org.openecomp.sdc.be.model.Component containerComponent = null;
1162             Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1163             RequirementCapabilityRelDef foundRelation = null;
1164
1165             validateUserExists(userId, "get relation by Id", false);
1166
1167             if(resultOp == null){
1168                 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1169                 if (validateComponentExists.isRight()) {
1170                     resultOp = Either.right(validateComponentExists.right().value());
1171                 }
1172             }
1173             if(resultOp == null){
1174                 containerComponent = validateComponentExists.left().value();
1175                 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1176                 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1177                 if(foundRelation == null){
1178                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1179                     log.debug("Relation with id {} was not found on the component", relationId, componentId);
1180                     resultOp = Either.right(responseFormat);
1181                 }
1182             }
1183             if(resultOp == null){
1184                 resultOp = setRelatedCapability(foundRelation, containerComponent);
1185             }
1186             if(resultOp.isLeft()){
1187                 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1188             }
1189         } catch (Exception e) {
1190             log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1191             resultOp =  Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1192         }
1193         return resultOp;
1194     }
1195
1196     private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1197         for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1198             if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1199                 return relationship;
1200             }
1201         }
1202         return null;
1203     }
1204
1205     private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1206         Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1207         RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1208         String instanceId = foundRelation.getFromNode();
1209         Optional<RequirementDefinition> foundRequirement;
1210         Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1211         if(!instance.isPresent()){
1212             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1213             log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1214             result = Either.right(responseFormat);
1215         }
1216         if(result == null){
1217             for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1218                 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1219                 if(foundRequirement.isPresent()){
1220                     foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1221                     result = Either.left(foundRelation);
1222                 }
1223             }
1224         }
1225         if(result == null){
1226             Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1227             if(getfulfilledRequirementRes.isRight()){
1228                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1229                 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1230                 result = Either.right(responseFormat);
1231             } else {
1232                 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1233             }
1234         }
1235         if(result == null){
1236             result = Either.left(foundRelation);
1237         }
1238         return result;
1239     }
1240
1241     private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1242         return  req.getName().equals(relationshipInfo.getRequirement()) &&
1243             req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1244             req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1245     }
1246
1247     private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1248         Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1249         RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1250         String instanceId = foundRelation.getToNode();
1251         Optional<CapabilityDefinition> foundCapability;
1252         Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1253         if(!instance.isPresent()){
1254             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1255             log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1256             result = Either.right(responseFormat);
1257         }
1258         if(result == null){
1259             for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1260                 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1261                 if(foundCapability.isPresent()){
1262                     foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1263                     result = Either.left(foundRelation);
1264                 }
1265             }
1266         }
1267         if(result == null){
1268             Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1269                     toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1270             if(getfulfilledRequirementRes.isRight()){
1271                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1272                 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1273                 result = Either.right(responseFormat);
1274             } else {
1275                 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1276             }
1277         }
1278         if(result == null){
1279             result = Either.left(foundRelation);
1280         }
1281         return result;
1282     }
1283
1284     private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1285         return     cap.getName().equals(relationshipInfo.getCapability()) &&
1286                 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1287                 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1288     }
1289
1290     private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1291         Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1292         Either<ComponentInstanceProperty, ResponseFormat> result;
1293         if (eitherAttribute.isLeft()) {
1294             log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1295             ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1296
1297             result = Either.left(instanceAttribute);
1298
1299         } else {
1300             log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1301
1302             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1303
1304             result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1305
1306         }
1307         return result;
1308     }
1309
1310     private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1311
1312         Either<ComponentInstanceProperty, ResponseFormat> result;
1313
1314         Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1315         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1316         validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1317
1318         if (!errorWrapper.isEmpty()) {
1319             result = Either.right(errorWrapper.getInnerElement());
1320         } else {
1321             Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1322             if (eitherAttribute.isLeft()) {
1323                 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1324                 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1325                 result = Either.left(instanceAttribute);
1326
1327             } else {
1328                 log.debug("Failed to add attribute value {}  to resource instance {}", attribute, resourceInstanceId);
1329
1330                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1331                 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1332
1333             }
1334         }
1335         return result;
1336     }
1337
1338     /**
1339      * Create Or Updates Attribute Instance
1340      *
1341      * @param componentTypeEnum
1342      * @param componentId
1343      * @param resourceInstanceId
1344      * @param attribute
1345      * @param userId
1346      * @return
1347      */
1348     public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1349         Either<ComponentInstanceProperty, ResponseFormat> result = null;
1350         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1351
1352         validateUserExist(userId, "create Or Update Attribute Value");
1353         if (errorWrapper.isEmpty()) {
1354             validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1355         }
1356         if (errorWrapper.isEmpty()) {
1357             validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1358         }
1359         if (errorWrapper.isEmpty()) {
1360             validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1361         }
1362
1363         try {
1364             if (errorWrapper.isEmpty()) {
1365                 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1366                 if (isCreate) {
1367                     result = createAttributeValue(attribute, resourceInstanceId);
1368                 } else {
1369                     result = updateAttributeValue(attribute, resourceInstanceId);
1370                 }
1371             } else {
1372                 result = Either.right(errorWrapper.getInnerElement());
1373             }
1374             return result;
1375         }
1376
1377         finally {
1378             if (result == null || result.isRight()) {
1379                 titanDao.rollback();
1380             } else {
1381                 titanDao.commit();
1382             }
1383             // unlock resource
1384             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1385         }
1386     }
1387
1388     private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1389         return StringUtils.isNotEmpty(property.getValue())
1390                 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1391                 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1392     }
1393
1394     // US833308 VLI in service - specific network_role property value logic
1395     private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1396         for (ComponentInstanceProperty property: properties) {
1397             if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1398                 ComponentParametersView componentParametersView = new ComponentParametersView();
1399                 componentParametersView.disableAll();
1400                 componentParametersView.setIgnoreComponentInstances(false);
1401                 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1402                 if (getServiceResult.isRight()) {
1403                     return getServiceResult.right().value();
1404                 }
1405                 Component service = getServiceResult.left().value();
1406                 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1407                 if (!getInstance.isPresent()) {
1408                     return StorageOperationStatus.NOT_FOUND;
1409                 }
1410                 String prefix = service.getSystemName() + ".";
1411                 String value = property.getValue();
1412                 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1413                     property.setValue(prefix + value);
1414                 }
1415             }
1416         }
1417         return StorageOperationStatus.OK;
1418     }
1419
1420     public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1421
1422         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1423
1424         /*-------------------------------Validations---------------------------------*/
1425
1426         validateUserExists(userId, "create Or Update Properties Values", false);
1427
1428         if (componentTypeEnum == null) {
1429             BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO);
1430             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1431             return resultOp;
1432         }
1433         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1434
1435         if (getResourceResult.isRight()) {
1436             log.debug("Failed to retrieve component, component id {}", componentId);
1437             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1438             return resultOp;
1439         }
1440         Component containerComponent = getResourceResult.left().value();
1441
1442         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1443             log.info("Restricted operation for user: {} on service {}", userId, componentId);
1444             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1445             return resultOp;
1446         }
1447         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1448         if (resourceInstanceStatus.isRight()) {
1449             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1450             return resultOp;
1451         }
1452         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1453         // specific property value logic US833308
1454         StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1455         if (StorageOperationStatus.OK != fetchByIdsStatus) {
1456             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1457             return resultOp;
1458         }
1459         // lock resource
1460         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1461         if (lockStatus != StorageOperationStatus.OK) {
1462             log.debug("Failed to lock service {}", componentId);
1463             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1464             return resultOp;
1465         }
1466
1467         try {
1468             for (ComponentInstanceProperty property: properties) {
1469                 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1470                 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1471                         responseFormat -> Either.right(responseFormat));
1472             }
1473
1474             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1475             if (updateContainerRes.isRight()) {
1476                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1477                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1478                 return resultOp;
1479             }
1480             resultOp = Either.left(properties);
1481             return resultOp;
1482
1483         } finally {
1484             if (resultOp == null || resultOp.isRight()) {
1485                 titanDao.rollback();
1486             } else {
1487                 titanDao.commit();
1488             }
1489             // unlock resource
1490             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1491         }
1492     }
1493
1494     private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1495                                                                         String capabilityType, String capabilityName) {
1496         String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1497         StringBuffer sb = new StringBuffer(componentInstanceUniqueId);
1498         sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1499         String capKey = sb.toString();
1500
1501         Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1502                 .orElse(Collections.emptyMap());
1503         List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1504         Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1505         if (cap.isPresent()) {
1506             List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1507             if (capProperties != null) {
1508                 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1509                 StorageOperationStatus status;
1510                 if (instanceProperty.isPresent()) {
1511                     instanceProperty.get().setValue(newValue);
1512                     List<String> path = new ArrayList<>();
1513                     path.add(componentInstanceUniqueId);
1514                     path.add(capKey);
1515                     instanceProperty.get().setPath(path);
1516                     status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1517                     if (status != StorageOperationStatus.OK) {
1518                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1519                         return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1520
1521                     }
1522                     foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1523                 }
1524             }
1525         }
1526
1527
1528         return componentsUtils.getResponseFormat(ActionStatus.OK);
1529     }
1530
1531     private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1532         List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1533         Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1534         StorageOperationStatus status;
1535         instanceProperty.get().setValue(newValue);
1536         if (instanceProperty.isPresent()) {
1537             status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1538         } else {
1539             status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1540         }
1541         if (status != StorageOperationStatus.OK) {
1542             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1543             return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1544         }
1545         List<String> path = new ArrayList<>();
1546         path.add(foundResourceInstance.getUniqueId());
1547         property.setPath(path);
1548
1549         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1550         return componentsUtils.getResponseFormat(ActionStatus.OK);
1551     }
1552
1553     private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1554         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1555         if (allDataTypesEither.isRight()) {
1556             TitanOperationStatus status = allDataTypesEither.right().value();
1557             BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1558             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1559         }
1560         Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1561         String innerType = null;
1562         String propertyType = property.getType();
1563         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1564         log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1565
1566         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1567             SchemaDefinition def = property.getSchema();
1568             if (def == null) {
1569                 log.debug("Schema doesn't exists for property of type {}", type);
1570                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1571             }
1572             PropertyDataDefinition propDef = def.getProperty();
1573             if (propDef == null) {
1574                 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1575                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1576             }
1577             innerType = propDef.getType();
1578         }
1579         // Specific Update Logic
1580         Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1581         String newValue = property.getValue();
1582         if (isValid.isRight()) {
1583             Boolean res = isValid.right().value();
1584             if (res == false) {
1585                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1586             }
1587         } else {
1588             Object object = isValid.left().value();
1589             if (object != null) {
1590                 newValue = object.toString();
1591             }
1592         }
1593         if (!isInput) {
1594             ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1595             if (pair.getRight() != null && pair.getRight() == false) {
1596                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1597                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1598             }
1599         }
1600         return Either.left(newValue);
1601     }
1602
1603     private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1604         List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1605         Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1606         StorageOperationStatus status;
1607         if (instanceProperty.isPresent()) {
1608             instanceProperty.get().setValue(input.getValue());
1609             status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1610         } else {
1611             status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1612         }
1613         if (status != StorageOperationStatus.OK) {
1614             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1615             return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1616         }
1617         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1618         return componentsUtils.getResponseFormat(ActionStatus.OK);
1619     }
1620
1621     public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1622
1623         Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1624
1625         validateUserExists(userId, "create Or Update Property Value", false);
1626
1627         if (componentTypeEnum == null) {
1628             BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1629             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1630             return resultOp;
1631         }
1632         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1633
1634         if (getResourceResult.isRight()) {
1635             log.debug("Failed to retrieve component, component id {}", componentId);
1636             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1637             return resultOp;
1638         }
1639         Component containerComponent = getResourceResult.left().value();
1640
1641         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1642             log.info("Restricted operation for user: {} on service {}", userId, componentId);
1643             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1644             return resultOp;
1645         }
1646         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1647         if (resourceInstanceStatus.isRight()) {
1648             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1649             return resultOp;
1650         }
1651
1652         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1653
1654         // lock resource
1655         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1656         if (lockStatus != StorageOperationStatus.OK) {
1657             log.debug("Failed to lock service {}", componentId);
1658             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1659             return resultOp;
1660         }
1661         try {
1662             for (ComponentInstanceInput input: inputs) {
1663                 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1664                 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1665                         responseFormat -> Either.right(responseFormat));
1666
1667             }
1668             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1669
1670             if (updateContainerRes.isRight()) {
1671                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1672                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1673                 return resultOp;
1674             }
1675             resultOp = Either.left(inputs);
1676             return resultOp;
1677
1678         } finally {
1679             if (resultOp == null || resultOp.isRight()) {
1680                 titanDao.rollback();
1681             } else {
1682                 titanDao.commit();
1683             }
1684             // unlock resource
1685             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1686         }
1687
1688     }
1689
1690     public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1691         String userId) {
1692
1693         Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1694
1695         validateUserExists(userId, "create Or Update Property Value", false);
1696
1697         if (componentTypeEnum == null) {
1698             BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1699             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1700             return resultOp;
1701         }
1702
1703         if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1704             log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1705             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1706             return resultOp;
1707         }
1708         // lock resource
1709         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1710         if (lockStatus != StorageOperationStatus.OK) {
1711             log.debug("Failed to lock service {}", componentId);
1712             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1713             return resultOp;
1714         }
1715         try {
1716             String propertyValueUid = property.getValueUniqueUid();
1717
1718             if (propertyValueUid == null) {
1719
1720                 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1721
1722                 if (counterRes.isRight()) {
1723                     log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1724                     StorageOperationStatus status = counterRes.right().value();
1725                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1726                     resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1727                 }
1728                 Integer index = counterRes.left().value();
1729                 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1730
1731                 if (result.isLeft()) {
1732                     log.trace("Property value was added to resource instance {}", resourceInstanceId);
1733                     ComponentInstanceProperty instanceProperty = result.left().value();
1734
1735                     resultOp = Either.left(instanceProperty);
1736
1737                 } else {
1738                     log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1739
1740                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1741
1742                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1743                 }
1744
1745             } else {
1746                 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1747
1748                 if (result.isLeft()) {
1749                     log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1750                     ComponentInstanceProperty instanceProperty = result.left().value();
1751
1752                     resultOp = Either.left(instanceProperty);
1753
1754                 } else {
1755                     log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1756
1757                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1758
1759                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1760                 }
1761             }
1762             if (resultOp.isLeft()) {
1763                 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1764                 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1765                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1766
1767                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1768
1769                 }
1770             }
1771             return resultOp;
1772
1773         } finally {
1774             if (resultOp == null || resultOp.isRight()) {
1775                 titanDao.rollback();
1776             } else {
1777                 titanDao.commit();
1778             }
1779             // unlock resource
1780             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1781         }
1782
1783     }
1784
1785     public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1786
1787         Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1788
1789         validateUserExists(userId, "create Or Update Input Value", false);
1790
1791         if (componentTypeEnum == null) {
1792             BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1793             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1794             return resultOp;
1795         }
1796
1797         if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1798             log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1799             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1800             return resultOp;
1801         }
1802         // lock resource
1803         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1804         if (lockStatus != StorageOperationStatus.OK) {
1805             log.debug("Failed to lock service {}", componentId);
1806             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1807             return resultOp;
1808         }
1809         try {
1810             String propertyValueUid = inputProperty.getValueUniqueUid();
1811             if (propertyValueUid == null) {
1812
1813                 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1814
1815                 if (counterRes.isRight()) {
1816                     log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1817                     StorageOperationStatus status = counterRes.right().value();
1818                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1819                     resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1820                 }
1821                 Integer index = counterRes.left().value();
1822                 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1823
1824                 if (result.isLeft()) {
1825                     log.debug("Property value was added to resource instance {}", resourceInstanceId);
1826                     ComponentInstanceInput instanceProperty = result.left().value();
1827
1828                     resultOp = Either.left(instanceProperty);
1829                     return resultOp;
1830
1831                 } else {
1832                     log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1833
1834                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1835
1836                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1837
1838                     return resultOp;
1839                 }
1840
1841             } else {
1842                 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1843
1844                 if (result.isLeft()) {
1845                     log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1846                     ComponentInstanceInput instanceProperty = result.left().value();
1847
1848                     resultOp = Either.left(instanceProperty);
1849                     return resultOp;
1850
1851                 } else {
1852                     log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1853
1854                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1855
1856                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1857
1858                     return resultOp;
1859                 }
1860             }
1861
1862         } finally {
1863             if (resultOp == null || resultOp.isRight()) {
1864                 titanDao.rollback();
1865             } else {
1866                 titanDao.commit();
1867             }
1868             // unlock resource
1869             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1870         }
1871
1872     }
1873
1874     public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1875
1876         validateUserExists(userId, "delete Property Value", false);
1877
1878         Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1879
1880         if (componentTypeEnum == null) {
1881             BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1882             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1883             return resultOp;
1884         }
1885
1886         if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1887             log.info("Restricted operation for user {} on service {}", userId, serviceId);
1888             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1889             return resultOp;
1890         }
1891         // lock resource
1892         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1893         if (lockStatus != StorageOperationStatus.OK) {
1894             log.debug("Failed to lock service {}", serviceId);
1895             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1896             return resultOp;
1897         }
1898         try {
1899             Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1900
1901             if (result.isLeft()) {
1902                 log.debug("Property value {} was removed from graph.", propertyValueId);
1903                 ComponentInstanceProperty instanceProperty = result.left().value();
1904
1905                 resultOp = Either.left(instanceProperty);
1906                 return resultOp;
1907
1908             } else {
1909                 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1910
1911                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1912
1913                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1914
1915                 return resultOp;
1916             }
1917
1918         } finally {
1919             if (resultOp == null || resultOp.isRight()) {
1920                 titanDao.rollback();
1921             } else {
1922                 titanDao.commit();
1923             }
1924             // unlock resource
1925             graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1926         }
1927
1928     }
1929
1930     private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1931
1932         Either<Component, ResponseFormat> eitherResponse = null;
1933         ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1934         Component component;
1935         ResponseFormat errorResponse;
1936         Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1937         if (getComponentRes.isRight()) {
1938             log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1939             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1940             errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1941             eitherResponse = Either.right(errorResponse);
1942         }
1943         if (eitherResponse == null) {
1944             component = getComponentRes.left().value();
1945             LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1946             if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1947                 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1948                 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1949                 eitherResponse = Either.right(errorResponse);
1950             }
1951         }
1952         if (eitherResponse == null) {
1953             eitherResponse = Either.left(getComponentRes.left().value());
1954         }
1955         return eitherResponse;
1956     }
1957
1958       public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
1959                                                                                 String containerComponentId,
1960                                                                                 String componentInstanceId,
1961                                                                                 ComponentInstance newComponentInstance) {
1962         Either<Set<String>, ResponseFormat> resultOp;
1963         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1964         if (validateComponentType.isRight()) {
1965           return Either.right(validateComponentType.right().value());
1966         }
1967         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1968         ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
1969
1970         //Fetch Component
1971         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
1972             validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
1973         if (validateComponentExists.isRight()) {
1974           return Either.right(validateComponentExists.right().value());
1975         }
1976         Component containerComponent = validateComponentExists.left().value();
1977
1978         //Fetch current component instance
1979         Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
1980             getResourceInstanceById(containerComponent, componentInstanceId);
1981         if (eitherResourceInstance.isRight()) {
1982           resultOp = Either.right(componentsUtils.getResponseFormat(
1983               ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
1984           return resultOp;
1985         }
1986         ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
1987
1988         //Check whether new componentInstance exists
1989         String resourceId = newComponentInstance.getComponentUid();
1990         Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
1991         if (componentExistsRes.isRight()) {
1992           log.debug("Failed to find resource ", resourceId);
1993           resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
1994               (componentExistsRes.right().value()), resourceId));
1995           return resultOp;
1996         } else if (!componentExistsRes.left().value()) {
1997           log.debug("The resource {} not found ", resourceId);
1998           resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
1999           return resultOp;
2000         }
2001
2002         //Fetch component using new component instance uid
2003         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2004         if (eitherResourceName.isRight()) {
2005           resultOp = Either.right(eitherResourceName.right().value());
2006           return resultOp;
2007         }
2008         Component updatedContainerComponent=eitherResourceName.left().value();
2009         Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2010             currentResourceInstance, updatedContainerComponent);
2011         resultOp=Either.left(toDeleteForwardingPaths);
2012
2013         return resultOp;
2014       }
2015
2016     private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2017                                            Component updatedContainerComponent) {
2018         DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2019         dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2020
2021         Service service = (Service) containerComponent;
2022         ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2023
2024         return forwardingPathUtils.
2025             getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2026     }
2027
2028     private ComponentParametersView getComponentParametersViewForForwardingPath() {
2029         ComponentParametersView componentParametersView = new ComponentParametersView();
2030         componentParametersView.setIgnoreCapabiltyProperties(false);
2031         componentParametersView.setIgnoreForwardingPath(false);
2032         return componentParametersView;
2033     }
2034
2035     public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2036
2037         User user = validateUserExists(userId, "change Component Instance Version", false);
2038
2039         Either<ComponentInstance, ResponseFormat> resultOp = null;
2040
2041         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2042         if (validateComponentType.isRight()) {
2043             return Either.right(validateComponentType.right().value());
2044         }
2045
2046         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2047         ComponentParametersView componentParametersView = new ComponentParametersView();
2048         componentParametersView.setIgnoreCapabiltyProperties(false);
2049         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2050         if (validateComponentExists.isRight()) {
2051             return Either.right(validateComponentExists.right().value());
2052         }
2053         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2054
2055         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2056         if (validateCanWorkOnComponent.isRight()) {
2057             return Either.right(validateCanWorkOnComponent.right().value());
2058         }
2059
2060         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2061         if (resourceInstanceStatus.isRight()) {
2062             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2063             return resultOp;
2064         }
2065
2066         ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2067
2068         return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2069     }
2070
2071     public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2072                                                                            ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType    ) {
2073         Either<ComponentInstance, ResponseFormat> resultOp = null;
2074         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2075
2076         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2077         String containerComponentId = containerComponent.getUniqueId();
2078         String componentInstanceId = currentResourceInstance.getUniqueId();
2079         if (lockComponent.isRight()) {
2080             return Either.right(lockComponent.right().value());
2081         }
2082
2083         try {
2084
2085
2086             if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2087                 resultOp = Either.left(currentResourceInstance);
2088                 return resultOp;
2089
2090             }
2091             String resourceId = newComponentInstance.getComponentUid();
2092
2093
2094
2095             Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2096             if (componentExistsRes.isRight()) {
2097                 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2098                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2099                 return resultOp;
2100             } else if (!componentExistsRes.left().value()) {
2101                 log.debug("The resource {} not found ", resourceId);
2102                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2103                 return resultOp;
2104             }
2105
2106             Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2107
2108             if (eitherOriginComponent.isRight()) {
2109                 resultOp = Either.right(eitherOriginComponent.right().value());
2110                 return resultOp;
2111             }
2112             DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2113             resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2114             if (resultOp.isRight()) {
2115                 log.debug("failed to delete resource instance {}", resourceId);
2116                 return resultOp;
2117             }
2118             ComponentInstance resResourceInfo = resultOp.left().value();
2119             Component origComponent = null;
2120             OriginTypeEnum originType = currentResourceInstance.getOriginType();
2121             if (originType == OriginTypeEnum.ServiceProxy) {
2122                 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2123                 if (serviceProxyOrigin.isRight()) {
2124                     log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2125                     return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2126                 }
2127                 origComponent = serviceProxyOrigin.left().value();
2128
2129                 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2130
2131                 if (fillProxyRes != StorageOperationStatus.OK) {
2132                     log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2133                     return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2134
2135                 }
2136                 newComponentInstance.setOriginType(originType);
2137             }else{
2138
2139
2140                 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2141
2142                 if (eitherResourceName.isRight()) {
2143                     resultOp = Either.right(eitherResourceName.right().value());
2144                     return resultOp;
2145                 }
2146
2147                 origComponent = eitherResourceName.left().value();
2148
2149                 newComponentInstance.setName(resResourceInfo.getName());
2150             }
2151
2152             newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2153             newComponentInstance.setPosX(resResourceInfo.getPosX());
2154             newComponentInstance.setPosY(resResourceInfo.getPosY());
2155             newComponentInstance.setDescription(resResourceInfo.getDescription());
2156
2157             resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2158
2159             if (resultOp.isRight()) {
2160                 log.debug("failed to create resource instance {}", resourceId);
2161                 return resultOp;
2162             }
2163
2164             ComponentInstance updatedComponentInstance = resultOp.left().value();
2165             if (resultOp.isRight()) {
2166                 log.debug("failed to create resource instance {}", resourceId);
2167                 return resultOp;
2168             }
2169
2170             Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2171             if (mergeStatusEither.isRight()) {
2172                 return Either.right(mergeStatusEither.right().value());
2173             }
2174
2175             ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2176             if (postChangeVersionResult != ActionStatus.OK) {
2177                 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2178             }
2179
2180             ComponentParametersView filter = new ComponentParametersView(true);
2181             filter.setIgnoreComponentInstances(false);
2182             Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2183             if (updatedComponentRes.isRight()) {
2184                 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2185                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2186                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2187                 log.debug("Component with id {} was not found", containerComponentId);
2188                 return Either.right(responseFormat);
2189             }
2190             resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2191             if (resourceInstanceStatus.isRight()) {
2192                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2193                 return resultOp;
2194             }
2195             resultOp = Either.left(resourceInstanceStatus.left().value());
2196             return resultOp;
2197
2198         } finally {
2199             unlockComponent(resultOp, containerComponent);
2200         }
2201     }
2202
2203     // US831698
2204     public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2205         final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2206         Component containerComponent = null;
2207
2208         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2209         try {
2210             validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2211
2212             Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2213             if (validateComponentType.isRight()) {
2214                 resultOp = Either.right(validateComponentType.right().value());
2215                 return resultOp;
2216             }
2217
2218             Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2219             if (validateContainerComponentExists.isRight()) {
2220                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2221                 return resultOp;
2222             }
2223             containerComponent = validateContainerComponentExists.left().value();
2224
2225             Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2226             if (resourceInstanceStatus.isRight()) {
2227                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2228                 return resultOp;
2229             }
2230
2231             List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2232             if (CollectionUtils.isEmpty(instanceProperties)) {
2233                 instanceProperties = new ArrayList<>();
2234             }
2235             resultOp = Either.left(instanceProperties);
2236             return resultOp;
2237         } finally {
2238             unlockComponent(resultOp, containerComponent);
2239         }
2240     }
2241
2242     protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2243         Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2244
2245         if (counterRes.isRight()) {
2246             log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2247             StorageOperationStatus status = counterRes.right().value();
2248             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2249             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2250         } else {
2251             instaceCounterWrapper.setInnerElement(counterRes.left().value());
2252         }
2253
2254     }
2255
2256     /**
2257      * updates componentInstance modificationTime
2258      *
2259      * @param componentInstance
2260      * @param componentInstanceType
2261      * @param modificationTime
2262      * @param inTransaction
2263      * @return
2264      */
2265     public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2266         Either<ComponentInstanceData, ResponseFormat> result;
2267         Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2268                 inTransaction);
2269         if (updateComponentInstanceRes.isRight()) {
2270             log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2271             result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2272         } else {
2273             result = Either.left(updateComponentInstanceRes.left().value());
2274         }
2275         return result;
2276     }
2277
2278     public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2279         // TODO Add implementation
2280         Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2281         return result;
2282     }
2283
2284     public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2285         // TODO Add implementation
2286         Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2287         return result;
2288     }
2289
2290     public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2291         // TODO Add implementation
2292         Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2293         return result;
2294     }
2295
2296     private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2297         return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2298     }
2299
2300     private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2301
2302         Either<ComponentInstance, StorageOperationStatus> result = null;
2303         List<ComponentInstance> instances = containerComponent.getComponentInstances();
2304         Optional<ComponentInstance> foundInstance = null;
2305         if (CollectionUtils.isEmpty(instances)) {
2306             result = Either.right(StorageOperationStatus.NOT_FOUND);
2307         }
2308         if (result == null) {
2309             foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2310             if (!foundInstance.isPresent()) {
2311                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2312             }
2313         }
2314         if (result == null) {
2315             result = Either.left(foundInstance.get());
2316         }
2317         return result;
2318     }
2319
2320     private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2321
2322         Long creationDate = origInstanceForUpdate.getCreationTime();
2323
2324         Long modificationTime = System.currentTimeMillis();
2325         resourceInstanceForUpdate.setCreationTime(creationDate);
2326         resourceInstanceForUpdate.setModificationTime(modificationTime);
2327
2328         resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2329
2330         if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2331             resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2332         }
2333
2334         resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2335
2336         if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2337             resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2338
2339         if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2340             resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2341
2342         if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2343             resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2344
2345         if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2346             resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2347
2348         if (resourceInstanceForUpdate.getOriginType() == null) {
2349             resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2350         }
2351         if(resourceInstanceForUpdate.getOriginType()  == OriginTypeEnum.ServiceProxy)
2352             resourceInstanceForUpdate.setIsProxy(true);
2353         if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2354             resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2355         }
2356         if (resourceInstanceForUpdate.getSourceModelName() == null) {
2357             resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2358         }
2359         if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2360             resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2361         }
2362         if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2363             resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2364         }
2365         return resourceInstanceForUpdate;
2366     }
2367     /**
2368      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2369      * @param containerComponentType
2370      * @param containerComponentId
2371      * @param componentInstanceUniqueId
2372      * @param capabilityType
2373      * @param capabilityName
2374      * @param userId
2375      * @param ownerId
2376      * @return
2377      */
2378     public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2379
2380         Component containerComponent = null;
2381
2382         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2383         try {
2384             validateUserExists(userId, "Get Component Instance Properties By Id", false);
2385             if(resultOp == null){
2386                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2387                 if (validateComponentType.isRight()) {
2388                     resultOp = Either.right(validateComponentType.right().value());
2389                 }
2390             }
2391             if(resultOp == null){
2392                 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2393                 if (validateContainerComponentExists.isRight()) {
2394                     resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2395                 } else {
2396                     containerComponent = validateContainerComponentExists.left().value();
2397                 }
2398             }
2399             if(resultOp == null){
2400                 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2401                 if (resourceInstanceStatus.isRight()) {
2402                     resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2403                 } else {
2404                     resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2405                 }
2406             }
2407             return resultOp;
2408         } finally {
2409             unlockComponent(resultOp, containerComponent);
2410         }
2411     }
2412
2413     private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2414         Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2415         CapabilityDefinition foundCapability;
2416         if (MapUtils.isNotEmpty(instanceCapabilities)) {
2417             List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2418             if (capabilitiesPerType != null) {
2419                 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2420                 if (capabilityOpt.isPresent()) {
2421                     foundCapability = capabilityOpt.get();
2422                     result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2423                 }
2424             }
2425         }
2426         if (result == null) {
2427             result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2428         }
2429         return result;
2430     }
2431
2432     private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2433         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2434         try {
2435             Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2436             if(getComponentInstanceCapabilityProperties.isRight()){
2437                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2438             } else {
2439                 resultOp =  Either.left(getComponentInstanceCapabilityProperties.left().value());
2440             }
2441         } catch(Exception e){
2442             log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2443             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2444         }
2445         return resultOp;
2446     }
2447
2448     private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2449                                                                         String capabilityType, String capabilityName, String ownerId) {
2450         String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2451         StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2452         sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2453         String capKey = sb.toString();
2454
2455         Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2456                 .orElse(Collections.emptyMap());
2457         List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2458         Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2459         if (cap.isPresent()) {
2460             List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2461             if (capProperties != null) {
2462                 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2463                 StorageOperationStatus status;
2464                 if (instanceProperty.isPresent()) {
2465                     instanceProperty.get().setValue(newValue);
2466                     List<String> path = new ArrayList<>();
2467                     path.add(componentInstanceUniqueId);
2468                     path.add(capKey);
2469                     instanceProperty.get().setPath(path);
2470                     status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2471                     if (status != StorageOperationStatus.OK) {
2472                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2473                         return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2474
2475                     }
2476                     foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2477                 }
2478             }
2479         }
2480         return componentsUtils.getResponseFormat(ActionStatus.OK);
2481     }
2482
2483     public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2484                                                                                                       List<ComponentInstanceProperty> properties, String userId) {
2485         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2486
2487         validateUserExists(userId, "update instance capability property", false);
2488
2489         if (componentTypeEnum == null) {
2490             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2491             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2492         }
2493         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2494
2495         if (getResourceResult.isRight()) {
2496             log.debug("Failed to retrieve component, component id {}", containerComponentId);
2497             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2498         }
2499         Component containerComponent = getResourceResult.left().value();
2500
2501         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2502             log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2503             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2504         }
2505         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2506         if (resourceInstanceStatus.isRight()) {
2507             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2508         }
2509         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2510         // lock resource
2511         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2512         if (lockStatus != StorageOperationStatus.OK) {
2513             log.debug("Failed to lock component {}", containerComponentId);
2514             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2515         }
2516
2517         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2518         if (allDataTypes.isRight()) {
2519             TitanOperationStatus status = allDataTypes.right().value();
2520             BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2521             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2522         }
2523
2524         try {
2525             for (ComponentInstanceProperty property : properties) {
2526                 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2527                 newPropertyValueEither.bimap(updatedValue ->
2528                         updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2529                     responseFormat -> Either.right(responseFormat));
2530             }
2531             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2532
2533             if (updateContainerRes.isRight()) {
2534                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2535                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2536                 return resultOp;
2537             }
2538             resultOp = Either.left(properties);
2539             return resultOp;
2540
2541         } finally {
2542             if (resultOp == null || resultOp.isRight()) {
2543                 titanDao.rollback();
2544             } else {
2545                 titanDao.commit();
2546             }
2547             // unlock resource
2548             graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2549         }
2550     }
2551
2552     public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2553         List<ComponentInstanceProperty> properties, String userId) {
2554         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2555
2556         validateUserExists(userId, "update instance capability property", false);
2557
2558         if (componentTypeEnum == null) {
2559             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2560             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2561         }
2562         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2563
2564         if (getResourceResult.isRight()) {
2565             log.debug("Failed to retrieve component, component id {}", containerComponentId);
2566             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2567         }
2568         Component containerComponent = getResourceResult.left().value();
2569
2570         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2571             log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2572             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2573         }
2574         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2575         if (resourceInstanceStatus.isRight()) {
2576             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2577         }
2578         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2579         // lock resource
2580         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2581         if (lockStatus != StorageOperationStatus.OK) {
2582             log.debug("Failed to lock component {}", containerComponentId);
2583             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2584         }
2585
2586         try {
2587             for (ComponentInstanceProperty property : properties) {
2588                 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2589                 newPropertyValueEither.bimap(updatedValue ->
2590                                 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2591                         responseFormat -> Either.right(responseFormat));
2592             }
2593             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2594
2595             if (updateContainerRes.isRight()) {
2596                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2597                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2598                 return resultOp;
2599             }
2600             resultOp = Either.left(properties);
2601             return resultOp;
2602
2603         } finally {
2604             if (resultOp == null || resultOp.isRight()) {
2605                 titanDao.rollback();
2606             } else {
2607                 titanDao.commit();
2608             }
2609             // unlock resource
2610             graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2611         }
2612     }
2613 }