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