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