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