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