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