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