Sonar code smell fixes
[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             Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2240             if (mergeStatusEither.isRight()) {
2241                 return Either.right(mergeStatusEither.right().value());
2242             }
2243
2244             ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2245             if (postChangeVersionResult != ActionStatus.OK) {
2246                 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2247             }
2248
2249             ComponentParametersView filter = new ComponentParametersView(true);
2250             filter.setIgnoreComponentInstances(false);
2251             Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2252             if (updatedComponentRes.isRight()) {
2253                 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2254                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2255                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2256                 log.debug("Component with id {} was not found", containerComponentId);
2257                 return Either.right(responseFormat);
2258             }
2259             resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2260             if (resourceInstanceStatus.isRight()) {
2261                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2262                 return resultOp;
2263             }
2264             resultOp = Either.left(resourceInstanceStatus.left().value());
2265             return resultOp;
2266
2267         } finally {
2268             unlockComponent(resultOp, containerComponent);
2269         }
2270     }
2271
2272     // US831698
2273     public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2274         final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2275         Component containerComponent = null;
2276
2277         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2278         try {
2279             validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2280
2281             Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2282             if (validateComponentType.isRight()) {
2283                 resultOp = Either.right(validateComponentType.right().value());
2284                 return resultOp;
2285             }
2286
2287             Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2288             if (validateContainerComponentExists.isRight()) {
2289                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2290                 return resultOp;
2291             }
2292             containerComponent = validateContainerComponentExists.left().value();
2293
2294             Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2295             if (resourceInstanceStatus.isRight()) {
2296                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2297                 return resultOp;
2298             }
2299
2300             List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2301             if (CollectionUtils.isEmpty(instanceProperties)) {
2302                 instanceProperties = new ArrayList<>();
2303             }
2304             resultOp = Either.left(instanceProperties);
2305             return resultOp;
2306         } finally {
2307             unlockComponent(resultOp, containerComponent);
2308         }
2309     }
2310
2311     protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2312         Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2313
2314         if (counterRes.isRight()) {
2315             log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2316             StorageOperationStatus status = counterRes.right().value();
2317             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2318             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2319         } else {
2320             instaceCounterWrapper.setInnerElement(counterRes.left().value());
2321         }
2322
2323     }
2324
2325     /**
2326      * updates componentInstance modificationTime
2327      *
2328      * @param componentInstance
2329      * @param componentInstanceType
2330      * @param modificationTime
2331      * @param inTransaction
2332      * @return
2333      */
2334     public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2335         Either<ComponentInstanceData, ResponseFormat> result;
2336         Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2337                 inTransaction);
2338         if (updateComponentInstanceRes.isRight()) {
2339             log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2340             result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2341         } else {
2342             result = Either.left(updateComponentInstanceRes.left().value());
2343         }
2344         return result;
2345     }
2346
2347     public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2348         // TODO Add implementation
2349         Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2350         return result;
2351     }
2352
2353     public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2354         // TODO Add implementation
2355         Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2356         return result;
2357     }
2358
2359     public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2360         // TODO Add implementation
2361         Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2362         return result;
2363     }
2364
2365     private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2366         return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2367     }
2368
2369     private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2370
2371         Either<ComponentInstance, StorageOperationStatus> result = null;
2372         List<ComponentInstance> instances = containerComponent.getComponentInstances();
2373         Optional<ComponentInstance> foundInstance = null;
2374         if (CollectionUtils.isEmpty(instances)) {
2375             result = Either.right(StorageOperationStatus.NOT_FOUND);
2376         }
2377         if (result == null) {
2378             foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2379             if (!foundInstance.isPresent()) {
2380                 result = Either.right(StorageOperationStatus.NOT_FOUND);
2381             }
2382         }
2383         if (result == null) {
2384             result = Either.left(foundInstance.get());
2385         }
2386         return result;
2387     }
2388
2389     private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2390
2391         Long creationDate = origInstanceForUpdate.getCreationTime();
2392
2393         Long modificationTime = System.currentTimeMillis();
2394         resourceInstanceForUpdate.setCreationTime(creationDate);
2395         resourceInstanceForUpdate.setModificationTime(modificationTime);
2396
2397         resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2398
2399         if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2400             resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2401         }
2402
2403         resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2404
2405         if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2406             resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2407
2408         if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2409             resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2410
2411         if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2412             resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2413
2414         if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2415             resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2416
2417         if (resourceInstanceForUpdate.getOriginType() == null) {
2418             resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2419         }
2420         if(resourceInstanceForUpdate.getOriginType()  == OriginTypeEnum.ServiceProxy)
2421             resourceInstanceForUpdate.setIsProxy(true);
2422         if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2423             resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2424         }
2425         if (resourceInstanceForUpdate.getSourceModelName() == null) {
2426             resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2427         }
2428         if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2429             resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2430         }
2431         if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2432             resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2433         }
2434         return resourceInstanceForUpdate;
2435     }
2436     /**
2437      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2438      * @param containerComponentType
2439      * @param containerComponentId
2440      * @param componentInstanceUniqueId
2441      * @param capabilityType
2442      * @param capabilityName
2443      * @param userId
2444      * @param ownerId
2445      * @return
2446      */
2447     public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2448
2449         Component containerComponent = null;
2450
2451         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2452         try {
2453             validateUserExists(userId, "Get Component Instance Properties By Id", false);
2454             if(resultOp == null){
2455                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2456                 if (validateComponentType.isRight()) {
2457                     resultOp = Either.right(validateComponentType.right().value());
2458                 }
2459             }
2460             if(resultOp == null){
2461                 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2462                 if (validateContainerComponentExists.isRight()) {
2463                     resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2464                 } else {
2465                     containerComponent = validateContainerComponentExists.left().value();
2466                 }
2467             }
2468             if(resultOp == null){
2469                 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2470                 if (resourceInstanceStatus.isRight()) {
2471                     resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2472                 } else {
2473                     resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2474                 }
2475             }
2476             return resultOp;
2477         } finally {
2478             unlockComponent(resultOp, containerComponent);
2479         }
2480     }
2481
2482     private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2483         Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2484         CapabilityDefinition foundCapability;
2485         if (MapUtils.isNotEmpty(instanceCapabilities)) {
2486             List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2487             if (capabilitiesPerType != null) {
2488                 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2489                 if (capabilityOpt.isPresent()) {
2490                     foundCapability = capabilityOpt.get();
2491                     result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2492                 }
2493             }
2494         }
2495         if (result == null) {
2496             result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2497         }
2498         return result;
2499     }
2500
2501     private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2502         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2503         try {
2504             Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2505             if(getComponentInstanceCapabilityProperties.isRight()){
2506                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2507             } else {
2508                 resultOp =  Either.left(getComponentInstanceCapabilityProperties.left().value());
2509             }
2510         } catch(Exception e){
2511             log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2512             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2513         }
2514         return resultOp;
2515     }
2516
2517     private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2518                                                                         String capabilityType, String capabilityName, String ownerId) {
2519         String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2520         StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2521         sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2522         String capKey = sb.toString();
2523
2524         Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2525                 .orElse(Collections.emptyMap());
2526         List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2527         Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2528         if (cap.isPresent()) {
2529             List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2530             if (capProperties != null) {
2531                 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2532                 StorageOperationStatus status;
2533                 if (instanceProperty.isPresent()) {
2534                     instanceProperty.get().setValue(newValue);
2535                     List<String> path = new ArrayList<>();
2536                     path.add(componentInstanceUniqueId);
2537                     path.add(capKey);
2538                     instanceProperty.get().setPath(path);
2539                     status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2540                     if (status != StorageOperationStatus.OK) {
2541                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2542                         return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2543
2544                     }
2545                     foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2546                 }
2547             }
2548         }
2549         return componentsUtils.getResponseFormat(ActionStatus.OK);
2550     }
2551
2552     public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2553                                                                                                       List<ComponentInstanceProperty> properties, String userId) {
2554         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2555
2556         validateUserExists(userId, "update instance capability property", false);
2557
2558         if (componentTypeEnum == null) {
2559             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2560             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2561         }
2562         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2563
2564         if (getResourceResult.isRight()) {
2565             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2566             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2567         }
2568         Component containerComponent = getResourceResult.left().value();
2569
2570         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2571             log.info("Restricted operation for user: {sourcePropList} on component {}", userId, containerComponentId);
2572             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2573         }
2574         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2575         if (resourceInstanceStatus.isRight()) {
2576             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2577         }
2578         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2579         // lock resource
2580         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2581         if (lockStatus != StorageOperationStatus.OK) {
2582             log.debug("Failed to lock component {}", containerComponentId);
2583             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2584         }
2585
2586         Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2587         if (allDataTypes.isRight()) {
2588             TitanOperationStatus status = allDataTypes.right().value();
2589             BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2590             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2591         }
2592
2593         try {
2594             for (ComponentInstanceProperty property : properties) {
2595                 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2596                 newPropertyValueEither.bimap(updatedValue ->
2597                                 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2598                         Either::right);
2599             }
2600             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2601
2602             if (updateContainerRes.isRight()) {
2603                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2604                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2605                 return resultOp;
2606             }
2607             resultOp = Either.left(properties);
2608             return resultOp;
2609
2610         } finally {
2611             if (resultOp == null || resultOp.isRight()) {
2612                 titanDao.rollback();
2613             } else {
2614                 titanDao.commit();
2615             }
2616             // unlock resource
2617             graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2618         }
2619     }
2620
2621     public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2622                                                                                                       List<ComponentInstanceProperty> properties, String userId) {
2623         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2624
2625         validateUserExists(userId, "update instance capability property", false);
2626
2627         if (componentTypeEnum == null) {
2628             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2629             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2630         }
2631         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2632
2633         if (getResourceResult.isRight()) {
2634             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2635             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2636         }
2637         Component containerComponent = getResourceResult.left().value();
2638
2639         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2640             log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2641             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2642         }
2643         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2644         if (resourceInstanceStatus.isRight()) {
2645             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2646         }
2647         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2648         // lock resource
2649         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2650         if (lockStatus != StorageOperationStatus.OK) {
2651             log.debug("Failed to lock component {}", containerComponentId);
2652             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2653         }
2654
2655         try {
2656             for (ComponentInstanceProperty property : properties) {
2657                 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2658                 newPropertyValueEither.bimap(updatedValue ->
2659                                 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2660                         Either::right);
2661             }
2662             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2663
2664             if (updateContainerRes.isRight()) {
2665                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2666                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2667                 return resultOp;
2668             }
2669             resultOp = Either.left(properties);
2670             return resultOp;
2671
2672         } finally {
2673             if (resultOp == null || resultOp.isRight()) {
2674                 titanDao.rollback();
2675             } else {
2676                 titanDao.commit();
2677             }
2678             // unlock resource
2679             graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2680         }
2681     }
2682
2683     public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2684                                                                                         String containerComponentId,
2685                                                                                         String componentInstanceId,
2686                                                                                         String userId) {
2687
2688         Map<String, ComponentInstance> resultMap = new HashMap<>();
2689         Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2690         if (getOrigComponent.isRight()) {
2691             log.error("Failed to get the original component information");
2692             return Either.right(componentsUtils.getResponseFormat(
2693                     ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2694         }
2695
2696         Component origComponent = getOrigComponent.left().value();
2697
2698         Either<Boolean, ResponseFormat> lockComponent = lockComponent(origComponent, "copyComponentInstance");
2699         if (lockComponent.isRight()) {
2700             log.error("destComponentInstance's data is {}", origComponent.toString());
2701             return Either.right(lockComponent.right().value());
2702         }
2703
2704
2705         Either<ComponentInstance, ResponseFormat> actionResponse = null;
2706         try {
2707             actionResponse = createComponentInstance(
2708                     "services", containerComponentId, userId, inputComponentInstance, true, false);
2709
2710             if (actionResponse.isRight()) {
2711                 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
2712                 return Either.right(componentsUtils.getResponseFormat(
2713                         ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2714             }
2715
2716         } finally {
2717
2718             // on failure of the create instance unlock the resource and rollback the transaction.
2719             if (null == actionResponse || actionResponse.isRight()) {
2720                 titanDao.rollback();
2721             }
2722             unlockComponent(actionResponse, origComponent);
2723         }
2724
2725         Either<String, ResponseFormat> resultOp = null;
2726
2727         try {
2728             ComponentInstance destComponentInstance = actionResponse.left().value();
2729             log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2730
2731
2732             resultOp = deepCopyComponentInstance(
2733                     origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2734
2735             if (resultOp.isRight()) {
2736                 log.error("Failed to deep copy component instance");
2737                 return Either.right(componentsUtils.getResponseFormat(
2738                         ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2739             }
2740             resultMap.put("componentInstance", destComponentInstance);
2741             return Either.left(resultMap);
2742         } finally {
2743
2744             if (resultOp == null || resultOp.isRight()) {
2745                 titanDao.rollback();
2746
2747             } else {
2748                 titanDao.commit();
2749                 log.debug("Success trasaction commit");
2750             }
2751             // unlock resource
2752             unlockComponent(resultOp, origComponent);
2753         }
2754     }
2755
2756     private Either<String, ResponseFormat> deepCopyComponentInstance(
2757             Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2758             ComponentInstance destComponentInstance, String userId) {
2759
2760         Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2761         if (getDestComponent.isRight()) {
2762             log.error("Failed to get the dest component information");
2763             return Either.right(componentsUtils.getResponseFormat(
2764                     ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2765         }
2766
2767         Component destComponent = getDestComponent.left().value();
2768
2769         Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2770                 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2771         if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2772             log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2773             return Either.right(componentsUtils.getResponseFormat(
2774                     ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2775         }
2776
2777         Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2778                 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2779         if (copyComponentInstanceWithAttributes.isRight()) {
2780             log.error("Failed to copy component instance with attributes as part of deep copy");
2781             return Either.right(componentsUtils.getResponseFormat(
2782                     ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2783         }
2784         return Either.left(COPY_COMPONENT_INSTANCE_OK);
2785     }
2786
2787     private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2788             Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2789             ComponentInstance destComponentInstance, String userId) {
2790         log.debug("start to copy ComponentInstance with properties and inputs");
2791
2792         List<ComponentInstanceProperty> sourcePropList = null;
2793         if (sourceComponent.getComponentInstancesProperties() != null
2794                 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2795             sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2796             log.debug("sourcePropList");
2797         }
2798
2799         List<ComponentInstanceProperty> destPropList = null;
2800         String destComponentInstanceId = destComponentInstance.getUniqueId();
2801         log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2802         if (destComponent.getComponentInstancesProperties() != null
2803                 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2804             destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2805             log.debug("destPropList {}");
2806         }
2807
2808         List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2809
2810         if (null != destPropList && null != sourcePropList) {
2811             log.debug("start to set property and attribute");
2812             for (ComponentInstanceProperty destProp : destPropList) {
2813                 String destPropertyName = destProp.getName();
2814                 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2815                     if (!destPropertyName.equals(sourceProp.getName())) {
2816                         continue;
2817                     }
2818                     log.debug("now set property");
2819                     if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2820                             && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2821                         log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2822
2823                         destProp.setValue(sourceProp.getValue());
2824                         Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2825                                 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2826                         if (updatePropertyValueEither.isRight()) {
2827                             log.error("Failed to copy the property {}", destPropertyName);
2828                             return Either.right(componentsUtils.getResponseFormat(
2829                                     ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2830                         }
2831                         break;
2832                     }
2833
2834                     log.debug("Now start to update inputs");
2835
2836                     if (sourceProp.getGetInputValues() != null) {
2837                         if (sourceProp.getGetInputValues().isEmpty()) {
2838                             log.debug("source property input values empty");
2839                             break;
2840                         }
2841                         log.debug("Now starting to copy the {} property", destPropertyName);
2842
2843                         Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2844                                 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2845                         if (getSourceInputDefaultValue.isRight()) {
2846                             return Either.right(getSourceInputDefaultValue.right().value());
2847                         }
2848                         componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2849                     }
2850                 }
2851             }
2852         }
2853         return Either.left(COPY_COMPONENT_INSTANCE_OK);
2854     }
2855
2856     private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
2857                                                                                Component destComponent,
2858                                                                                String sourceComponentInstanceId,
2859                                                                                ComponentInstance destComponentInstance,
2860                                                                                String userId) {
2861         String destComponentInstanceId = destComponentInstance.getUniqueId();
2862
2863         log.info("start to copy component instance with attributes");
2864
2865         List<ComponentInstanceProperty> sourceAttributeList = null;
2866         if (sourceComponent.getComponentInstancesAttributes() != null
2867                 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
2868             sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
2869             log.info("sourceAttributes {}");
2870         }
2871
2872         List<ComponentInstanceProperty> destAttributeList = null;
2873         if (destComponent.getComponentInstancesAttributes() != null
2874                 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
2875             destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
2876             log.info("destAttributeList {}");
2877         }
2878         if (null != sourceAttributeList && null != destAttributeList) {
2879             log.info("set attribute");
2880
2881             for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
2882                 String sourceAttributeName = sourceAttribute.getName();
2883                 for (ComponentInstanceProperty destAttribute : destAttributeList) {
2884                     if (sourceAttributeName.equals(destAttribute.getName())) {
2885                         if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
2886                             log.debug("Start to copy the attribute exists {}", sourceAttributeName);
2887
2888                             sourceAttribute.setUniqueId(
2889                                     UniqueIdBuilder.buildResourceInstanceUniuqeId(
2890                                             "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
2891
2892                             Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
2893                                     createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
2894                                             destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
2895                                             userId);
2896                             if (updateAttributeValueEither.isRight()) {
2897                                 log.error("Failed to copy the attribute");
2898                                 return Either.right(componentsUtils
2899                                         .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
2900                                                 "Failed to paste component instance to the canvas, attribute copy"));
2901                             }
2902                             break;
2903                         }
2904                     }
2905                 }
2906             }
2907         }
2908
2909         return Either.left(COPY_COMPONENT_INSTANCE_OK);
2910     }
2911
2912     private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
2913                                                                                                        String componentId,
2914                                                                                                        String resourceInstanceId,
2915                                                                                                        ComponentInstanceProperty attribute,
2916                                                                                                        String userId) {
2917
2918         Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2919
2920         validateUserExists(userId, "Create or Update attribute value", false);
2921
2922         if (componentTypeEnum == null) {
2923             BeEcompErrorManager.getInstance().logInvalidInputError(
2924                     "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2925             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2926             return resultOp;
2927         }
2928
2929         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2930
2931         if (getResourceResult.isRight()) {
2932             log.info("Failed to retrieve component id {}", componentId);
2933             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2934             return resultOp;
2935         }
2936
2937         Component containerComponent = getResourceResult.left().value();
2938
2939         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2940
2941         if (resourceInstanceStatus.isRight()) {
2942             resultOp = Either.right(componentsUtils.getResponseFormat(
2943                     ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
2944             return resultOp;
2945         }
2946
2947         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2948
2949
2950         String propertyType = attribute.getType();
2951         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2952         log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
2953
2954         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2955             SchemaDefinition def = attribute.getSchema();
2956             if (def == null) {
2957                 log.info("Schema doesn't exists for attribute of type {}", type);
2958                 return Either.right(componentsUtils.getResponseFormat(
2959                         componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2960             }
2961             PropertyDataDefinition propDef = def.getProperty();
2962             if (propDef == null) {
2963                 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
2964                 return Either.right(componentsUtils.getResponseFormat(
2965                         componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2966             }
2967         }
2968
2969         List<ComponentInstanceProperty> instanceAttributes = containerComponent.
2970                 getComponentInstancesAttributes().get(resourceInstanceId);
2971         Optional<ComponentInstanceProperty> instanceAttribute =
2972                 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
2973         StorageOperationStatus status;
2974
2975         if (instanceAttribute.isPresent()) {
2976             log.info("updateComponentInstanceAttribute");
2977             status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
2978         } else {
2979             log.info("addComponentInstanceAttribute");
2980             status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
2981         }
2982         if (status != StorageOperationStatus.OK) {
2983             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2984             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2985             return resultOp;
2986         }
2987         List<String> path = new ArrayList<>();
2988         path.add(foundResourceInstance.getUniqueId());
2989         attribute.setPath(path);
2990
2991         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2992         Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
2993                 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2994
2995         if (updateContainerRes.isRight()) {
2996             ActionStatus actionStatus = componentsUtils.
2997                     convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2998             resultOp = Either.right(componentsUtils.
2999                     getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3000             return resultOp;
3001         }
3002         resultOp = Either.left(attribute);
3003         return resultOp;
3004
3005
3006
3007     }
3008
3009     private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3010                                                                            String componentInstanceId,
3011                                                                            ComponentInstanceProperty property) {
3012         Either<String, ResponseFormat> resultOp;
3013         Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3014
3015         if (getComponent.isRight()) {
3016             log.error("Failed to get the component information");
3017             return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3018                     ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3019         }
3020
3021         Component containerComponent = getComponent.left().value();
3022
3023         StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3024                 containerComponent, componentInstanceId, property);
3025         if (status != StorageOperationStatus.OK) {
3026             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3027             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3028             return resultOp;
3029         }
3030
3031         Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3032                 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3033
3034         if (updateContainerRes.isRight()) {
3035             ActionStatus actionStatus = componentsUtils.
3036                     convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3037             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3038             return resultOp;
3039         }
3040
3041         return Either.left("Update OK");
3042     }
3043
3044     private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3045         List<InputDefinition> inputList = component.getInputs();
3046         for (InputDefinition input : inputList) {
3047             if (input.getUniqueId().equals(inputId)) {
3048                 if (input.getDefaultValue() == null) {
3049                     log.debug("The input's default value is null");
3050                     return Either.left(null);
3051                 }
3052                 return Either.left(input.getDefaultValue());
3053             }
3054         }
3055         log.error("The input's default value with id {} is not found", inputId);
3056         return Either.right(componentsUtils.getResponseFormat(
3057                 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3058     }
3059
3060     /**
3061      * Method to delete selected nodes and edges on composition page
3062      * @param containerComponentType
3063      * @param componentId
3064      * @param componentInstanceIdList
3065      * @param userId
3066      * @return
3067      */
3068     public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3069                                                                   String componentId,
3070                                                                   List<String> componentInstanceIdList,
3071                                                                   String userId) {
3072
3073         List<String> deleteErrorIds = new ArrayList<>();
3074         Map<String, List<String>> deleteErrorMap = new HashMap<>();
3075         Either<Component, ResponseFormat> validateResponse = validateUser(containerComponentType, componentId, userId);
3076         if (validateResponse.isRight()) {
3077             deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3078             return deleteErrorMap;
3079         }
3080         Component containerComponent = validateResponse.left().value();
3081
3082         Either<Boolean, ResponseFormat> lockComponent = lockComponent(
3083                 containerComponent, "batchDeleteComponentInstance");
3084         if (lockComponent.isRight()) {
3085             log.error("Failed to lockComponent containerComponent");
3086             deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3087             return deleteErrorMap;
3088         }
3089
3090         try {
3091             for (String eachInstanceId : componentInstanceIdList) {
3092                 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3093                         containerComponent, containerComponentType, componentId, eachInstanceId);
3094                 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3095                 if (actionResponse.isRight()) {
3096                     log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3097                     deleteErrorIds.add(eachInstanceId);
3098                 }
3099             }
3100             //sending the ids of the error nodes that were not deleted to UI
3101             deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3102             return deleteErrorMap;
3103         } finally {
3104             unlockComponent(validateResponse, containerComponent);
3105         }
3106     }
3107
3108     private Either<Component, ResponseFormat> validateUser(String containerComponentParam,
3109                                                            String containerComponentId,
3110                                                            String userId) {
3111         validateUserExists(userId, "delete Component Instance", false);
3112         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
3113         if (validateComponentType.isRight()) {
3114             log.error("ComponentType[{}] doesn't support", containerComponentParam);
3115             return Either.right(validateComponentType.right().value());
3116         }
3117
3118         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
3119         Either<Component, ResponseFormat> validateComponentExists = validateComponentExists(
3120                 containerComponentId, containerComponentType, null);
3121         if (validateComponentExists.isRight()) {
3122             log.error("Component Id[{}] doesn't exist", containerComponentId);
3123             return Either.right(validateComponentExists.right().value());
3124         }
3125
3126         Component containerComponent = validateComponentExists.left().value();
3127         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
3128         if (validateCanWorkOnComponent.isRight()) {
3129             return Either.right(validateCanWorkOnComponent.right().value());
3130         }
3131         return Either.left(containerComponent);
3132     }
3133
3134     private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3135                                                                                    String containerComponentType,
3136                                                                                    String containerComponentId,
3137                                                                                    String componentInstanceId) {
3138
3139         Either<ComponentInstance, ResponseFormat> resultOp;
3140         final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3141
3142         resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3143
3144         if (resultOp.isRight()) {
3145             log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3146             return Either.right(resultOp.right().value());
3147         }
3148
3149         log.info("Successfully deleted instance with id {}", componentInstanceId);
3150         return Either.left(resultOp.left().value());
3151     }
3152 }