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