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