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