7ea00b1d46ef18f993275e4a79b5664abaf1d841
[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                 ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent,
1961                     foundResourceInstance);
1962                 String propertyParentUniqueId = property.getParentUniqueId();
1963                 if (property.isGetFunction()) {
1964                     validateToscaGetFunction(property, containerComponent);
1965                     property.setValue(property.getToscaGetFunction().generatePropertyValue());
1966                 }
1967                 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, containerComponent.getModel());
1968                 if (updatedPropertyValue.isRight()) {
1969                     log.error("Failed to update property object value of property: {}",
1970                         property);
1971                     throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1972                 }
1973                 Optional<CapabilityDefinition>
1974                     capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1975                 if (capPropDefinition.isPresent()) {
1976                     updatedPropertyValue
1977                         .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1978                             containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1979                             capPropDefinition.get().getName()), Either::right);
1980                 } else {
1981                     updatedPropertyValue.bimap(
1982                         updatedValue -> {
1983                             componentInstanceProperty.setValue(updatedValue);
1984                             return updatePropertyOnContainerComponent(property, updatedValue,
1985                                 containerComponent, foundResourceInstance);
1986                         }, Either::right);
1987                     updatedProperties.add(componentInstanceProperty);
1988                 }
1989             }
1990
1991             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
1992                 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1993             if (updateContainerRes.isRight()) {
1994                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1995                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1996                 return resultOp;
1997             }
1998             resultOp = Either.left(updatedProperties);
1999             return resultOp;
2000
2001         } catch (final ComponentException e) {
2002             return Either.right(e.getResponseFormat());
2003         } finally {
2004             if (resultOp == null || resultOp.isRight()) {
2005                 janusGraphDao.rollback();
2006             } else {
2007                 janusGraphDao.commit();
2008             }
2009             // unlock resource
2010             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2011         }
2012     }
2013
2014     public Either<List<ComponentInstanceAttribute>, ResponseFormat> createOrUpdateAttributeValues(final ComponentTypeEnum componentTypeEnum,
2015                                                                                                   final String componentId,
2016                                                                                                   final String resourceInstanceId,
2017                                                                                                   final List<ComponentInstanceAttribute> attributes,
2018                                                                                                   final String userId) {
2019         Either<List<ComponentInstanceAttribute>, ResponseFormat> resultOp = null;
2020         /*-------------------------------Validations---------------------------------*/
2021         validateUserExists(userId);
2022
2023         if (componentTypeEnum == null) {
2024             BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2025             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2026             return resultOp;
2027         }
2028         final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade
2029             .getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2030
2031         if (getResourceResult.isRight()) {
2032             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2033             final ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2034             return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2035         }
2036         final Component containerComponent = getResourceResult.left().value();
2037
2038         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2039             if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2040                 log.info(COMPONENT_ARCHIVED, componentId);
2041                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2042             }
2043             log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2044             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2045         }
2046
2047         final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
2048             resourceInstanceId);
2049         if (resourceInstanceStatus.isRight()) {
2050             return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2051                 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2052         }
2053         final ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2054
2055         // lock resource
2056         final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2057         if (lockStatus != StorageOperationStatus.OK) {
2058             log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2059             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2060         }
2061         final List<ComponentInstanceAttribute> updatedProperties = new ArrayList<>();
2062         try {
2063             for (final ComponentInstanceAttribute attribute : attributes) {
2064                 final ComponentInstanceAttribute componentInstanceProperty = validateAttributeExistsOnComponent(attribute, containerComponent,
2065                     foundResourceInstance);
2066                 final Either<String, ResponseFormat> updatedPropertyValue = updateAttributeObjectValue(attribute);
2067                 if (updatedPropertyValue.isRight()) {
2068                     log.error("Failed to update attribute object value of attribute: {}", attribute);
2069                     throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
2070                 }
2071                 updatedPropertyValue.bimap(
2072                     updatedValue -> {
2073                         componentInstanceProperty.setValue(updatedValue);
2074                         return updateAttributeOnContainerComponent(attribute, updatedValue,
2075                             containerComponent, foundResourceInstance);
2076                     }, Either::right);
2077                 updatedProperties.add(componentInstanceProperty);
2078             }
2079
2080             final Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2081                 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2082             if (updateContainerRes.isRight()) {
2083                 final ActionStatus actionStatus = componentsUtils
2084                     .convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2085                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2086                 return resultOp;
2087             }
2088             resultOp = Either.left(updatedProperties);
2089             return resultOp;
2090
2091         } catch (final ComponentException e) {
2092             return Either.right(e.getResponseFormat());
2093         } finally {
2094             if (resultOp == null || resultOp.isRight()) {
2095                 janusGraphDao.rollback();
2096             } else {
2097                 janusGraphDao.commit();
2098             }
2099             // unlock resource
2100             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2101         }
2102     }
2103
2104     private void validateMandatoryFields(PropertyDataDefinition property) {
2105         if (StringUtils.isEmpty(property.getName())) {
2106             throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
2107         }
2108     }
2109
2110     private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
2111                                                                         ComponentInstance foundResourceInstance) {
2112         List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
2113             .get(foundResourceInstance.getUniqueId());
2114         Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName()))
2115             .findAny();
2116         if (instanceProperty.isEmpty()) {
2117             throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
2118         }
2119         return instanceProperty.get();
2120     }
2121
2122     private ComponentInstanceAttribute validateAttributeExistsOnComponent(final ComponentInstanceAttribute attribute,
2123                                                                           final Component containerComponent,
2124                                                                           final ComponentInstance foundResourceInstance) {
2125         final List<ComponentInstanceAttribute> instanceProperties =
2126             containerComponent.getComponentInstancesAttributes().get(foundResourceInstance.getUniqueId());
2127         final Optional<ComponentInstanceAttribute> instanceAttribute =
2128             instanceProperties.stream().filter(p -> p.getName().equals(attribute.getName())).findAny();
2129         if (!instanceAttribute.isPresent()) {
2130             throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, attribute.getName());
2131         }
2132         return instanceAttribute.get();
2133     }
2134
2135     private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
2136                                                                         String newValue, Component containerComponent,
2137                                                                         ComponentInstance foundResourceInstance,
2138                                                                         String capabilityType, String capabilityName) {
2139         String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2140         ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2141             foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2142         if (actionStatus != null) {
2143             return actionStatus;
2144         }
2145
2146         return componentsUtils.getResponseFormat(ActionStatus.OK);
2147     }
2148
2149     private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
2150                                                                   String newValue, Component containerComponent,
2151                                                                   ComponentInstance foundResourceInstance,
2152                                                                   String capabilityType, String capabilityName) {
2153         String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2154         Either<Component, StorageOperationStatus> getComponentRes =
2155             toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
2156         if (getComponentRes.isRight()) {
2157             return componentsUtils.getResponseFormat(getComponentRes.right().value());
2158         }
2159
2160         ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2161             foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2162         if (actionStatus != null) {
2163             return actionStatus;
2164         }
2165
2166         return componentsUtils.getResponseFormat(ActionStatus.OK);
2167     }
2168
2169     private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
2170                                                              Component containerComponent,
2171                                                              ComponentInstance foundResourceInstance,
2172                                                              String capabilityType, String capabilityName,
2173                                                              String componentInstanceUniqueId) {
2174         Map<String, List<CapabilityDefinition>> capabilities =
2175             Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
2176         List<CapabilityDefinition> capPerType =
2177             Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2178         Optional<CapabilityDefinition> cap =
2179             capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
2180         if (cap.isPresent()) {
2181             List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2182             if (capProperties != null) {
2183                 Optional<ComponentInstanceProperty> instanceProperty =
2184                     capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2185                 StorageOperationStatus status;
2186                 if (instanceProperty.isPresent()) {
2187                     String capKey = ModelConverter
2188                         .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
2189                             componentInstanceUniqueId, cap.get());
2190                     instanceProperty.get().setValue(newValue);
2191                     List<String> path = new ArrayList<>();
2192                     path.add(componentInstanceUniqueId);
2193                     path.add(capKey);
2194                     instanceProperty.get().setPath(path);
2195                     status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
2196                         componentInstanceUniqueId, capKey, instanceProperty.get());
2197                     if (status != StorageOperationStatus.OK) {
2198                         ActionStatus actionStatus =
2199                             componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2200                         return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2201
2202                     }
2203                     foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2204                 }
2205             }
2206         }
2207         return null;
2208     }
2209
2210     private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
2211                                                               Component containerComponent, ComponentInstance foundResourceInstance) {
2212         StorageOperationStatus status;
2213         instanceProperty.setValue(newValue);
2214         status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
2215         if (status != StorageOperationStatus.OK) {
2216             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2217             return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2218         }
2219         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2220         return componentsUtils.getResponseFormat(ActionStatus.OK);
2221     }
2222
2223     private ResponseFormat updateAttributeOnContainerComponent(final ComponentInstanceAttribute instanceAttribute,
2224                                                                final String newValue,
2225                                                                final Component containerComponent,
2226                                                                final ComponentInstance foundResourceInstance) {
2227
2228         instanceAttribute.setValue(newValue);
2229         final StorageOperationStatus status =
2230             toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), instanceAttribute);
2231         if (status != StorageOperationStatus.OK) {
2232             final ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2233             return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2234         }
2235         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2236         return componentsUtils.getResponseFormat(ActionStatus.OK);
2237     }
2238
2239     private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
2240         final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, property.getModel());
2241         String propertyType = property.getType();
2242         String innerType = getInnerType(property);
2243
2244         // Specific Update Logic
2245         Either<Object, Boolean> isValid = propertyOperation
2246             .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
2247         if (isValid.isRight()) {
2248             if (!Boolean.TRUE.equals(isValid.right().value())) {
2249                 log.error("Invalid value {} of property {} ", newValue, property.getName());
2250                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2251             }
2252         } else {
2253             Object object = isValid.left().value();
2254             if (object != null) {
2255                 newValue = object.toString();
2256             }
2257         }
2258         if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
2259             return Either.right(componentsUtils.getResponseFormat(componentsUtils
2260                 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2261         }
2262         return Either.left(newValue);
2263     }
2264
2265     private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
2266                                                                           String innerType, String propertyType) {
2267         if (!isInput) {
2268             ImmutablePair<String, Boolean> pair = propertyOperation
2269                 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2270             if (pair.getRight() != null && !pair.getRight()) {
2271                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2272                 return true;
2273             }
2274         }
2275         return false;
2276     }
2277
2278     private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, final String model) {
2279         final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, model);
2280         String innerType = null;
2281         String propertyType = property.getType();
2282         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2283         log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
2284
2285         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2286             SchemaDefinition schema = property.getSchema();
2287             if (schema == null) {
2288                 log.debug("Schema doesn't exists for property of type {}", type);
2289                 return Either
2290                     .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2291             }
2292             PropertyDataDefinition propDef = schema.getProperty();
2293             if (propDef == null) {
2294                 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
2295                 return Either
2296                     .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2297             }
2298             innerType = propDef.getType();
2299         }
2300
2301         // Specific Update Logic
2302         String newValue = property.getValue();
2303
2304         if (property.hasGetFunction()) {
2305             return Either.left(newValue);
2306         }
2307
2308         Either<Object, Boolean> isValid = propertyOperation
2309             .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
2310         if (isValid.isRight()) {
2311             if (!Boolean.TRUE.equals(isValid.right().value())) {
2312                 log.debug("validate and update property value has failed with value: {}", property.getValue());
2313                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2314                     DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2315             }
2316         } else {
2317             Object object = isValid.left().value();
2318             if (object != null) {
2319                 newValue = object.toString();
2320             }
2321         }
2322         ImmutablePair<String, Boolean> pair = propertyOperation
2323             .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2324         if (pair.getRight() != null && Boolean.FALSE.equals(pair.getRight())) {
2325             BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2326             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2327                 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2328         }
2329         return Either.left(newValue);
2330     }
2331
2332     private <T extends AttributeDefinition> Either<String, ResponseFormat> updateAttributeObjectValue(final T attribute) {
2333         String innerType = null;
2334         final String attributeType = attribute.getType();
2335         final ToscaPropertyType type = ToscaPropertyType.isValidType(attributeType);
2336         log.debug("The type of the attribute {} is {}", attribute.getUniqueId(), attributeType);
2337
2338         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2339             final SchemaDefinition def = attribute.getSchema();
2340             if (def == null) {
2341                 log.debug("Schema doesn't exists for attribute of type {}", type);
2342                 return Either
2343                     .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2344             }
2345             PropertyDataDefinition propDef = def.getProperty();
2346             if (propDef == null) {
2347                 log.debug("Property in Schema Definition inside attribute of type {} doesn't exist", type);
2348                 return Either
2349                     .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2350             }
2351             innerType = propDef.getType();
2352         }
2353
2354         // Specific Update Logic
2355         String newValue = attribute.getValue();
2356
2357         final var isValid = attributeOperation.validateAndUpdateAttributeValue(attribute, innerType,
2358             componentsUtils.getAllDataTypes(applicationDataTypeCache, attribute.getModel()));
2359         if (isValid.isRight()) {
2360             final Boolean res = isValid.right().value();
2361             if (!Boolean.TRUE.equals(res)) {
2362                 log.debug("validate and update attribute value has failed with value: {}", newValue);
2363                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2364                     DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2365             }
2366         } else {
2367             final Object object = isValid.left().value();
2368             if (object != null) {
2369                 newValue = object.toString();
2370             }
2371         }
2372         return Either.left(newValue);
2373     }
2374
2375     private <T extends PropertyDefinition> void validateToscaGetFunction(T property, Component parentComponent) {
2376         final ToscaGetFunctionDataDefinition toscaGetFunction = property.getToscaGetFunction();
2377         validateGetPropertySource(toscaGetFunction.getFunctionType(), toscaGetFunction.getPropertySource());
2378         if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_INPUT) {
2379             validateGetFunction(property, parentComponent.getInputs(), parentComponent.getModel());
2380             return;
2381         }
2382         if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_PROPERTY) {
2383             if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
2384                 validateGetFunction(property, parentComponent.getProperties(), parentComponent.getModel());
2385             } else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
2386                 final ComponentInstance componentInstance =
2387                     parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
2388                         .orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
2389                 validateGetFunction(property, componentInstance.getProperties(), parentComponent.getModel());
2390             }
2391
2392             return;
2393         }
2394
2395         throw ToscaGetFunctionExceptionSupplier.functionNotSupported(toscaGetFunction.getFunctionType()).get();
2396     }
2397
2398     private <T extends PropertyDefinition, U extends PropertyDefinition> void validateGetFunction(final T property,
2399                                                                                                   final List<U> parentProperties,
2400                                                                                                   final String model) {
2401         final ToscaGetFunctionDataDefinition toscaGetFunction = property.getToscaGetFunction();
2402         if (CollectionUtils.isEmpty(parentProperties)) {
2403             throw ToscaGetFunctionExceptionSupplier
2404                 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource(),
2405                     toscaGetFunction.getFunctionType()
2406                 ).get();
2407         }
2408         final String getFunctionPropertyUniqueId = toscaGetFunction.getPropertyUniqueId();
2409         T referredProperty = (T) parentProperties.stream()
2410             .filter(property1 -> getFunctionPropertyUniqueId.equals(property1.getUniqueId()))
2411             .findFirst()
2412             .orElseThrow(ToscaGetFunctionExceptionSupplier
2413                 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource()
2414                     , toscaGetFunction.getFunctionType())
2415             );
2416         if (toscaGetFunction.isSubProperty()) {
2417             referredProperty = findSubProperty(referredProperty, toscaGetFunction, model);
2418         }
2419
2420         if (!property.getType().equals(referredProperty.getType())) {
2421             throw ToscaGetFunctionExceptionSupplier
2422                 .propertyTypeDiverge(toscaGetFunction.getFunctionType(), referredProperty.getType(), property.getType()).get();
2423         }
2424         if (PropertyType.typeHasSchema(referredProperty.getType()) && !referredProperty.getSchemaType().equals(property.getSchemaType())) {
2425             throw ToscaGetFunctionExceptionSupplier
2426                 .propertySchemaDiverge(toscaGetFunction.getFunctionType(), referredProperty.getSchemaType(), property.getSchemaType()).get();
2427         }
2428     }
2429
2430     private <T extends PropertyDefinition> T findSubProperty(final T referredProperty, final ToscaGetFunctionDataDefinition toscaGetFunction,
2431                                                              final String model) {
2432         final Map<String, DataTypeDefinition> dataTypeMap = loadDataTypes(model);
2433         final List<String> propertyPathFromSource = toscaGetFunction.getPropertyPathFromSource();
2434         DataTypeDefinition dataType = dataTypeMap.get(referredProperty.getType());
2435         if (dataType == null) {
2436             throw ToscaGetFunctionExceptionSupplier
2437                 .propertyDataTypeNotFound(propertyPathFromSource.get(0), referredProperty.getType(), toscaGetFunction.getFunctionType()).get();
2438         }
2439         T foundProperty = referredProperty;
2440         for (int i = 1; i < propertyPathFromSource.size(); i++) {
2441             final String currentPropertyName = propertyPathFromSource.get(i);
2442             foundProperty = (T) dataType.getProperties().stream()
2443                 .filter(propertyDefinition -> currentPropertyName.equals(propertyDefinition.getName())).findFirst()
2444                 .orElseThrow(
2445                     ToscaGetFunctionExceptionSupplier
2446                         .propertyNotFoundOnTarget(propertyPathFromSource.subList(0, i), toscaGetFunction.getPropertySource(),
2447                             toscaGetFunction.getFunctionType())
2448                 );
2449             dataType = dataTypeMap.get(foundProperty.getType());
2450             if (dataType == null) {
2451                 throw ToscaGetFunctionExceptionSupplier
2452                     .propertyDataTypeNotFound(propertyPathFromSource.subList(0, i), foundProperty.getType(),
2453                         toscaGetFunction.getFunctionType()).get();
2454             }
2455         }
2456         return foundProperty;
2457     }
2458
2459     private Map<String, DataTypeDefinition> loadDataTypes(String model) {
2460         final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeEither =
2461             applicationDataTypeCache.getAll(model);
2462         if (dataTypeEither.isRight()) {
2463             throw ToscaGetFunctionExceptionSupplier.couldNotLoadDataTypes(model).get();
2464         }
2465         return dataTypeEither.left().value();
2466     }
2467
2468     private void validateGetPropertySource(final ToscaGetFunctionType functionType, final PropertySource propertySource) {
2469         if (functionType == ToscaGetFunctionType.GET_INPUT && propertySource != PropertySource.SELF) {
2470             throw ToscaGetFunctionExceptionSupplier
2471                 .targetSourceNotSupported(functionType, propertySource).get();
2472         }
2473         if (functionType == ToscaGetFunctionType.GET_PROPERTY && !List.of(PropertySource.SELF, PropertySource.INSTANCE).contains(propertySource)) {
2474             throw ToscaGetFunctionExceptionSupplier
2475                 .targetSourceNotSupported(functionType, propertySource).get();
2476         }
2477     }
2478
2479     private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
2480                                                            ComponentInstance foundResourceInstance) {
2481         StorageOperationStatus status;
2482         input.setValue(newValue);
2483         status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
2484         if (status != StorageOperationStatus.OK) {
2485             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2486             return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2487         }
2488         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2489         return componentsUtils.getResponseFormat(ActionStatus.OK);
2490     }
2491
2492     public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
2493                                                                                                   String componentId, String resourceInstanceId,
2494                                                                                                   List<ComponentInstanceInput> inputs,
2495                                                                                                   String userId) {
2496
2497         Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
2498
2499         validateUserExists(userId);
2500
2501         if (componentTypeEnum == null) {
2502             BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2503             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2504             return resultOp;
2505         }
2506         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2507
2508         if (getResourceResult.isRight()) {
2509             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2510             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2511             return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2512         }
2513         Component containerComponent = getResourceResult.left().value();
2514
2515         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2516             if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2517                 log.info(COMPONENT_ARCHIVED, componentId);
2518                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2519             }
2520             log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2521             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2522             return resultOp;
2523         }
2524         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2525         if (resourceInstanceStatus.isRight()) {
2526             return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2527                 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2528         }
2529
2530         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2531
2532         // lock resource
2533         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2534         if (lockStatus != StorageOperationStatus.OK) {
2535             log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2536             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2537         }
2538         List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
2539         try {
2540             for (ComponentInstanceInput input : inputs) {
2541                 validateMandatoryFields(input);
2542                 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
2543                 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
2544                 if (validatedInputValue.isRight()) {
2545                     throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2546                 }
2547                 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
2548                     foundResourceInstance);
2549                 updatedInputs.add(componentInstanceInput);
2550             }
2551             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2552                 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2553             if (updateContainerRes.isRight()) {
2554                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2555                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2556                 return resultOp;
2557             }
2558             resultOp = Either.left(updatedInputs);
2559             return resultOp;
2560
2561         } finally {
2562             if (resultOp == null || resultOp.isRight()) {
2563                 janusGraphDao.rollback();
2564             } else {
2565                 janusGraphDao.commit();
2566             }
2567             // unlock resource
2568             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2569         }
2570
2571     }
2572
2573     private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
2574                                                                   ComponentInstance foundResourceInstance) {
2575         List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2576         Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2577         if (!instanceInput.isPresent()) {
2578             throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2579         }
2580         return instanceInput.get();
2581     }
2582
2583     public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
2584                                                                                                       String componentId, String resourceInstanceId,
2585                                                                                                       String groupInstanceId,
2586                                                                                                       ComponentInstanceProperty property,
2587                                                                                                       String userId) {
2588
2589         Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2590
2591         validateUserExists(userId);
2592
2593         if (componentTypeEnum == null) {
2594             BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2595             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2596             return resultOp;
2597         }
2598
2599         if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2600             log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2601             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2602             return resultOp;
2603         }
2604         // lock resource
2605         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2606         if (lockStatus != StorageOperationStatus.OK) {
2607             log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2608             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2609             return resultOp;
2610         }
2611         try {
2612             String propertyValueUid = property.getValueUniqueUid();
2613
2614             if (propertyValueUid == null) {
2615
2616                 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
2617                     .increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2618
2619                 if (counterRes.isRight()) {
2620                     log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2621                     StorageOperationStatus status = counterRes.right().value();
2622                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2623                     resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2624                 }
2625                 Integer index = counterRes.left().value();
2626                 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2627                     .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2628
2629                 if (result.isLeft()) {
2630                     log.trace("Property value was added to resource instance {}", resourceInstanceId);
2631                     ComponentInstanceProperty instanceProperty = result.left().value();
2632
2633                     resultOp = Either.left(instanceProperty);
2634
2635                 } else {
2636                     log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2637
2638                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2639
2640                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2641                 }
2642
2643             } else {
2644                 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2645                     .updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2646
2647                 if (result.isLeft()) {
2648                     log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2649                     ComponentInstanceProperty instanceProperty = result.left().value();
2650
2651                     resultOp = Either.left(instanceProperty);
2652
2653                 } else {
2654                     log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2655
2656                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2657
2658                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2659                 }
2660             }
2661             if (resultOp.isLeft()) {
2662                 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2663                 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2664                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2665
2666                     resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2667
2668                 }
2669             }
2670             return resultOp;
2671
2672         } finally {
2673             if (resultOp == null || resultOp.isRight()) {
2674                 janusGraphDao.rollback();
2675             } else {
2676                 janusGraphDao.commit();
2677             }
2678             // unlock resource
2679             graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2680         }
2681
2682     }
2683
2684     public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
2685                                                                                  String resourceInstanceId, String propertyValueId, String userId) {
2686
2687         validateUserExists(userId);
2688
2689         Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2690
2691         if (componentTypeEnum == null) {
2692             BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2693             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2694             return resultOp;
2695         }
2696
2697         if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2698             log.info("Restricted operation for user {} on service {}", userId, serviceId);
2699             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2700             return resultOp;
2701         }
2702         // lock resource
2703         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2704         if (lockStatus != StorageOperationStatus.OK) {
2705             log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2706             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2707             return resultOp;
2708         }
2709         try {
2710             Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
2711                 .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2712
2713             if (result.isLeft()) {
2714                 log.debug("Property value {} was removed from graph.", propertyValueId);
2715                 ComponentInstanceProperty instanceProperty = result.left().value();
2716
2717                 resultOp = Either.left(instanceProperty);
2718                 return resultOp;
2719
2720             } else {
2721                 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2722
2723                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2724
2725                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2726
2727                 return resultOp;
2728             }
2729
2730         } finally {
2731             if (resultOp == null || resultOp.isRight()) {
2732                 janusGraphDao.rollback();
2733             } else {
2734                 janusGraphDao.commit();
2735             }
2736             // unlock resource
2737             graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2738         }
2739
2740     }
2741
2742     private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2743
2744         ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2745         Component component;
2746         Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2747         if (getComponentRes.isRight()) {
2748             log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
2749                 componentInstance.getName());
2750             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2751             throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2752         }
2753         component = getComponentRes.left().value();
2754         LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2755         if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2756             ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2757             throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2758         }
2759         if (Boolean.TRUE.equals(component.isArchived())) {
2760             ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2761             throw new ByActionStatusComponentException(actionStatus, component.getName());
2762         }
2763         final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2764         if (MapUtils.isNotEmpty(componentInterfaces)) {
2765             componentInterfaces.forEach(componentInstance::addInterface);
2766         }
2767         return component;
2768     }
2769
2770     public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2771                                                                              String containerComponentId,
2772                                                                              String componentInstanceId,
2773                                                                              ComponentInstance newComponentInstance) {
2774         Either<Set<String>, ResponseFormat> resultOp;
2775         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2776         ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2777
2778         //Fetch Component
2779         Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2780
2781         //Fetch current component instance
2782         Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2783             getResourceInstanceById(containerComponent, componentInstanceId);
2784         if (eitherResourceInstance.isRight()) {
2785             resultOp = Either.right(componentsUtils.getResponseFormat(
2786                 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2787             return resultOp;
2788         }
2789         ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2790
2791         //Check whether new componentInstance exists
2792         String resourceId = newComponentInstance.getComponentUid();
2793         Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2794         if (componentExistsRes.isRight()) {
2795             log.debug("Failed to find resource {}", resourceId);
2796             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2797                 (componentExistsRes.right().value()), resourceId));
2798             return resultOp;
2799         } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2800             log.debug("The resource {} not found ", resourceId);
2801             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2802             return resultOp;
2803         }
2804
2805         //Fetch component using new component instance uid
2806         Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2807         Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2808             currentResourceInstance, updatedContainerComponent);
2809         resultOp = Either.left(toDeleteForwardingPaths);
2810
2811         return resultOp;
2812     }
2813
2814     private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2815                                            Component updatedContainerComponent) {
2816         DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
2817         dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2818
2819         Service service = (Service) containerComponent;
2820         ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2821
2822         return forwardingPathUtils.
2823             getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
2824     }
2825
2826     private ComponentParametersView getComponentParametersViewForForwardingPath() {
2827         ComponentParametersView componentParametersView = new ComponentParametersView();
2828         componentParametersView.setIgnoreCapabiltyProperties(false);
2829         componentParametersView.setIgnoreServicePath(false);
2830         return componentParametersView;
2831     }
2832
2833     public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
2834                                                             String userId, ComponentInstance newComponentInstance) {
2835
2836         User user = validateUserExists(userId);
2837         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2838         ComponentParametersView componentParametersView = new ComponentParametersView();
2839         componentParametersView.setIgnoreCapabiltyProperties(false);
2840
2841         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
2842             componentParametersView);
2843
2844         validateCanWorkOnComponent(containerComponent, userId);
2845
2846         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2847         if (resourceInstanceStatus.isRight()) {
2848             throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
2849                 containerComponentId);
2850         }
2851
2852         ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2853
2854         return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
2855     }
2856
2857     public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
2858                                                    ComponentInstance currentResourceInstance,
2859                                                    ComponentInstance newComponentInstance,
2860                                                    User user,
2861                                                    final ComponentTypeEnum containerComponentType) {
2862         boolean failed = false;
2863         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2864
2865         try {
2866             lockComponent(containerComponent, "changeComponentInstanceVersion");
2867             String containerComponentId = containerComponent.getUniqueId();
2868             String componentInstanceId = currentResourceInstance.getUniqueId();
2869             if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2870                 return currentResourceInstance;
2871             }
2872             String resourceId = newComponentInstance.getComponentUid();
2873
2874             Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
2875                 .validateComponentExists(resourceId);
2876             if (componentExistsRes.isRight()) {
2877                 StorageOperationStatus errorStatus = componentExistsRes.right().value();
2878
2879                 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
2880                 throw new ByActionStatusComponentException(
2881                     componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
2882             } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2883                 log.debug("The resource {} not found ", resourceId);
2884                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2885             }
2886
2887             Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2888             DataForMergeHolder dataHolder = compInstMergeDataBL
2889                 .saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2890             ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
2891                 containerComponentType);
2892
2893             if (resResourceInfo == null) {
2894                 log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
2895                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2896             } else {
2897                 Component origComponent = null;
2898                 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2899                 newComponentInstance.setOriginType(originType);
2900                 if (originType == OriginTypeEnum.ServiceProxy) {
2901                     Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
2902                         .getLatestByName(SERVICE_PROXY, null);
2903                     if (isServiceProxyOrigin(serviceProxyOrigin)) {
2904                         throw new ByActionStatusComponentException(
2905                             componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2906                     }
2907                     origComponent = serviceProxyOrigin.left().value();
2908
2909                     StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2910
2911                     if (isFillProxyRes(fillProxyRes)) {
2912                         throw new ByActionStatusComponentException(
2913                             componentsUtils.convertFromStorageResponse(fillProxyRes));
2914                     }
2915                 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
2916                     final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
2917                         .getToscaFullElement(newComponentInstance.getComponentUid());
2918                     if (getServiceResult.isRight()) {
2919                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2920                     }
2921                     final Component service = getServiceResult.left().value();
2922
2923                     final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
2924                         .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
2925                     if (getServiceDerivedFromTypeResult.isRight()) {
2926                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2927                     }
2928
2929                     origComponent = getServiceDerivedFromTypeResult.left().value();
2930
2931                     final StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2932                     if (isFillProxyRes(fillProxyRes)) {
2933                         throw new ByActionStatusComponentException(
2934                             componentsUtils.convertFromStorageResponse(fillProxyRes));
2935                     }
2936                 } else {
2937                     origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2938                     newComponentInstance.setName(resResourceInfo.getName());
2939                     final Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade
2940                             .getToscaFullElement(newComponentInstance.getComponentUid());
2941                     if (getComponentRes.isRight()) {
2942                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
2943                     }
2944                     final Component component = getComponentRes.left().value();
2945                     final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2946                     if (MapUtils.isNotEmpty(componentInterfaces)) {
2947                         componentInterfaces.forEach(newComponentInstance::addInterface);
2948                     }
2949                 }
2950
2951                 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2952                 newComponentInstance.setPosX(resResourceInfo.getPosX());
2953                 newComponentInstance.setPosY(resResourceInfo.getPosY());
2954                 newComponentInstance.setDescription(resResourceInfo.getDescription());
2955                 newComponentInstance.setInstanceCount(resResourceInfo.getInstanceCount());
2956                 newComponentInstance.setMaxOccurrences(resResourceInfo.getMaxOccurrences());
2957                 newComponentInstance.setMinOccurrences(resResourceInfo.getMinOccurrences());
2958
2959                 ComponentInstance updatedComponentInstance =
2960                     createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2961                 dataHolder.setCurrInstanceNode(origComponent);
2962                 compInstMergeDataBL
2963                     .mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2964
2965                 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
2966                     .doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2967                 if (postChangeVersionResult != ActionStatus.OK) {
2968                     throw new ByActionStatusComponentException(postChangeVersionResult);
2969                 }
2970
2971                 ComponentParametersView filter = new ComponentParametersView(true);
2972                 filter.setIgnoreComponentInstances(false);
2973                 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2974                 if (updatedComponentRes.isRight()) {
2975                     StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2976                     ActionStatus actionStatus = componentsUtils
2977                         .convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2978                     log.debug("Component with id {} was not found", containerComponentId);
2979                     throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2980                 }
2981                 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
2982                     updatedComponentInstance.getUniqueId());
2983                 if (resourceInstanceStatus.isRight()) {
2984                     throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
2985                         (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
2986                 }
2987                 return resourceInstanceStatus.left().value();
2988             }
2989         } catch (ComponentException e) {
2990             failed = true;
2991             throw e;
2992         } finally {
2993             unlockComponent(failed, containerComponent);
2994         }
2995     }
2996
2997     private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
2998         if (fillProxyRes != StorageOperationStatus.OK) {
2999             log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
3000             return true;
3001         }
3002         return false;
3003     }
3004
3005     // US831698
3006     public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
3007                                                                               String componentInstanceUniqueId, String userId) {
3008         Component containerComponent = null;
3009
3010         boolean failed = false;
3011         try {
3012             validateUserExists(userId);
3013             validateComponentType(containerComponentTypeParam);
3014
3015             Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
3016             if (validateContainerComponentExists.isRight()) {
3017                 throw new ByActionStatusComponentException(
3018                     componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3019             }
3020             containerComponent = validateContainerComponentExists.left().value();
3021
3022             Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3023                 componentInstanceUniqueId);
3024             if (resourceInstanceStatus.isRight()) {
3025                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
3026                     containerComponentId);
3027             }
3028
3029             List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
3030             if (CollectionUtils.isEmpty(instanceProperties)) {
3031                 instanceProperties = new ArrayList<>();
3032             }
3033             return instanceProperties;
3034         } catch (ComponentException e) {
3035             failed = true;
3036             throw e;
3037         } finally {
3038             unlockComponent(failed, containerComponent);
3039         }
3040     }
3041
3042     public List<ComponentInstanceAttribute> getComponentInstanceAttributesById(final String containerComponentTypeParam,
3043                                                                                final String containerComponentId,
3044                                                                                final String componentInstanceUniqueId,
3045                                                                                final String userId) {
3046         Component containerComponent = null;
3047
3048         boolean failed = false;
3049         try {
3050             validateUserExists(userId);
3051             validateComponentType(containerComponentTypeParam);
3052
3053             final Either<Component, StorageOperationStatus> validateContainerComponentExists =
3054                 toscaOperationFacade.getToscaElement(containerComponentId);
3055             if (validateContainerComponentExists.isRight()) {
3056                 throw new ByActionStatusComponentException(
3057                     componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3058             }
3059             containerComponent = validateContainerComponentExists.left().value();
3060
3061             if (getResourceInstanceById(containerComponent, componentInstanceUniqueId).isRight()) {
3062                 throw new ByActionStatusComponentException(
3063                     ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
3064             }
3065
3066             final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = containerComponent.getComponentInstancesAttributes();
3067             return componentInstancesAttributes == null ? new ArrayList<>()
3068                 : componentInstancesAttributes.getOrDefault(componentInstanceUniqueId, new ArrayList<>());
3069         } catch (final ComponentException e) {
3070             failed = true;
3071             throw e;
3072         } finally {
3073             unlockComponent(failed, containerComponent);
3074         }
3075     }
3076
3077     protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType,
3078                                             Wrapper<Integer> instaceCounterWrapper,
3079                                             Wrapper<ResponseFormat> errorWrapper) {
3080         Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation
3081             .increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
3082
3083         if (counterRes.isRight()) {
3084             log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
3085             StorageOperationStatus status = counterRes.right().value();
3086             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3087             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
3088         } else {
3089             instaceCounterWrapper.setInnerElement(counterRes.left().value());
3090         }
3091
3092     }
3093
3094     /**
3095      * updates componentInstance modificationTime
3096      *
3097      * @param componentInstance
3098      * @param componentInstanceType
3099      * @param modificationTime
3100      * @param inTransaction
3101      * @return
3102      */
3103     public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
3104         ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
3105         Either<ComponentInstanceData, ResponseFormat> result;
3106         Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
3107             .updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
3108                 inTransaction);
3109         if (updateComponentInstanceRes.isRight()) {
3110             log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
3111                 updateComponentInstanceRes.right().value());
3112             result = Either
3113                 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
3114         } else {
3115             result = Either.left(updateComponentInstanceRes.left().value());
3116         }
3117         return result;
3118     }
3119
3120     public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
3121         // TODO Add implementation
3122         return Either.left(new ComponentInstance());
3123     }
3124
3125     public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
3126         // TODO Add implementation
3127         return Either.left(new ComponentInstance());
3128     }
3129
3130     public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
3131         // TODO Add implementation
3132         return Either.left(new ComponentInstance());
3133     }
3134
3135     private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
3136                                                              String newInstanceName) {
3137         return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
3138     }
3139
3140     private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(final Component containerComponent, final String instanceId) {
3141         final List<ComponentInstance> instances = containerComponent.getComponentInstances();
3142         if (CollectionUtils.isEmpty(instances)) {
3143             return Either.right(StorageOperationStatus.NOT_FOUND);
3144         }
3145
3146         final Optional<ComponentInstance> foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
3147         if (foundInstance.isEmpty()) {
3148             return Either.right(StorageOperationStatus.NOT_FOUND);
3149         }
3150
3151         return Either.left(foundInstance.get());
3152     }
3153
3154     private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
3155         Long creationDate = origInstanceForUpdate.getCreationTime();
3156         Long modificationTime = System.currentTimeMillis();
3157         resourceInstanceForUpdate.setCreationTime(creationDate);
3158         resourceInstanceForUpdate.setModificationTime(modificationTime);
3159         resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
3160         if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
3161             resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
3162         }
3163         resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
3164         if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
3165             resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
3166         }
3167         if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
3168             resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
3169         }
3170         if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
3171             resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
3172         }
3173         if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
3174             resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
3175         }
3176         if (resourceInstanceForUpdate.getOriginType() == null) {
3177             resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
3178         }
3179         if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
3180             resourceInstanceForUpdate.setIsProxy(true);
3181         }
3182         if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
3183             resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
3184         }
3185         if (resourceInstanceForUpdate.getSourceModelName() == null) {
3186             resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
3187         }
3188         if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
3189             resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
3190         }
3191         if (resourceInstanceForUpdate.getSourceModelUid() == null) {
3192             resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
3193         }
3194         if (resourceInstanceForUpdate.getCreatedFrom() == null) {
3195             resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
3196         }
3197         return resourceInstanceForUpdate;
3198     }
3199
3200     /**
3201      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3202      *
3203      * @param containerComponentType
3204      * @param containerComponentId
3205      * @param componentInstanceUniqueId
3206      * @param capabilityType
3207      * @param capabilityName
3208      * @param userId
3209      * @param ownerId
3210      * @return
3211      */
3212     public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
3213                                                                                         String componentInstanceUniqueId, String capabilityType,
3214                                                                                         String capabilityName, String ownerId, String userId) {
3215         Component containerComponent = null;
3216         List<ComponentInstanceProperty> resultOp = null;
3217         try {
3218             validateUserExists(userId);
3219             validateComponentType(containerComponentType);
3220             containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
3221             ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left()
3222                 .on(this::componentInstanceException);
3223             resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId,
3224                 resourceInstanceStatus.getCapabilities());
3225         } catch (StorageException | ComponentException e) {
3226             unlockRollbackWithException(containerComponent, e);
3227         } catch (Exception e) {
3228             unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
3229         }
3230         unlockWithCommit(containerComponent);
3231         return resultOp;
3232     }
3233
3234     private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
3235                                                                      String capabilityName, String ownerId,
3236                                                                      Map<String, List<CapabilityDefinition>> instanceCapabilities) {
3237         CapabilityDefinition foundCapability;
3238         if (MapUtils.isNotEmpty(instanceCapabilities)) {
3239             List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
3240             if (capabilitiesPerType != null) {
3241                 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
3242                     .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
3243                 if (capabilityOpt.isPresent()) {
3244                     foundCapability = capabilityOpt.get();
3245                     return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
3246                 }
3247             }
3248         }
3249         return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
3250     }
3251
3252     private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
3253                                                                                        String capabilityName, String ownerId) {
3254         try {
3255             return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
3256                 .left().on(this::componentInstancePropertyListException);
3257         } catch (Exception e) {
3258             log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
3259                 capabilityName, e);
3260             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
3261         }
3262     }
3263
3264     public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
3265                                                                                    String componentInstanceUniqueId,
3266                                                                                    RequirementDefinition requirementDef, String userId) {
3267         Either<RequirementDefinition, ResponseFormat> resultOp = null;
3268         validateUserExists(userId);
3269         if (componentTypeEnum == null) {
3270             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3271             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3272         }
3273         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3274         if (getResourceResult.isRight()) {
3275             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3276             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3277         }
3278         Component containerComponent = getResourceResult.left().value();
3279         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3280             log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3281             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3282         }
3283         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3284             componentInstanceUniqueId);
3285         if (resourceInstanceStatus.isRight()) {
3286             return Either.right(componentsUtils
3287                 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3288         }
3289         // lock resource
3290         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3291         if (lockStatus != StorageOperationStatus.OK) {
3292             log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3293             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3294         }
3295         try {
3296             StorageOperationStatus updateRequirementStatus = toscaOperationFacade
3297                 .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
3298             if (updateRequirementStatus != StorageOperationStatus.OK) {
3299                 log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
3300                     containerComponentId);
3301                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
3302             }
3303             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3304                 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3305             if (updateContainerRes.isRight()) {
3306                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3307                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3308                 return resultOp;
3309             }
3310             resultOp = Either.left(requirementDef);
3311             return resultOp;
3312         } finally {
3313             if (resultOp == null || resultOp.isRight()) {
3314                 janusGraphDao.rollback();
3315             } else {
3316                 janusGraphDao.commit();
3317             }
3318             // unlock resource
3319             graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3320         }
3321     }
3322
3323     public Either<CapabilityDefinition, ResponseFormat> updateInstanceCapability(final ComponentTypeEnum containerComponentType,
3324                                                                                  final String containerComponentId,
3325                                                                                  final String componentInstanceUniqueId,
3326                                                                                  final CapabilityDefinition capabilityDefinition,
3327                                                                                  final String userId) {
3328         if (containerComponentType == null) {
3329             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapability", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3330             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3331         }
3332         validateUserExists(userId);
3333         final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3334         if (getResourceResult.isRight()) {
3335             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3336             return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, containerComponentId));
3337         }
3338         final Component containerComponent = getResourceResult.left().value();
3339         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3340             log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3341             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3342         }
3343         final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus =
3344             getResourceInstanceById(containerComponent, componentInstanceUniqueId);
3345         if (resourceInstanceStatus.isRight()) {
3346             return Either.right(componentsUtils
3347                 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3348         }
3349         // lock resource
3350         final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, containerComponentType.getNodeType());
3351         if (lockStatus != StorageOperationStatus.OK) {
3352             log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3353             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3354         }
3355         var success = false;
3356         try {
3357             final CapabilityDataDefinition updatedCapabilityDefinition = toscaOperationFacade
3358                 .updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition);
3359             final Either<Component, StorageOperationStatus> updateContainerEither = toscaOperationFacade
3360                 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3361             if (updateContainerEither.isRight()) {
3362                 var actionStatus = componentsUtils.convertFromStorageResponse(updateContainerEither.right().value(), containerComponentType);
3363                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3364             }
3365             success = true;
3366             return Either.left(new CapabilityDefinition(updatedCapabilityDefinition));
3367         } catch (final BusinessException e) {
3368             log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3369                 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3370             throw e;
3371         } catch (final Exception e) {
3372             log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3373                 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3374             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3375         } finally {
3376             if (success) {
3377                 janusGraphDao.commit();
3378             } else {
3379                 janusGraphDao.rollback();
3380             }
3381             // unlock resource
3382             graphLockOperation.unlockComponent(containerComponentId, containerComponentType.getNodeType());
3383         }
3384     }
3385
3386     public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
3387                                                                                                       String containerComponentId,
3388                                                                                                       String componentInstanceUniqueId,
3389                                                                                                       String capabilityType, String capabilityName,
3390                                                                                                       List<ComponentInstanceProperty> properties,
3391                                                                                                       String userId) {
3392         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
3393         validateUserExists(userId);
3394         if (componentTypeEnum == null) {
3395             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3396             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3397         }
3398         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3399         if (getResourceResult.isRight()) {
3400             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3401             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3402         }
3403         Component containerComponent = getResourceResult.left().value();
3404         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3405             log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3406             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3407         }
3408         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3409             componentInstanceUniqueId);
3410         if (resourceInstanceStatus.isRight()) {
3411             return Either.right(componentsUtils
3412                 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3413         }
3414         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3415         // lock resource
3416         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3417         if (lockStatus != StorageOperationStatus.OK) {
3418             log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3419             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3420         }
3421         try {
3422             for (ComponentInstanceProperty property : properties) {
3423                 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
3424                 newPropertyValueEither.bimap(
3425                     updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
3426                         capabilityType, capabilityName), Either::right);
3427             }
3428             Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3429                 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3430             if (updateContainerRes.isRight()) {
3431                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3432                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3433                 return resultOp;
3434             }
3435             resultOp = Either.left(properties);
3436             return resultOp;
3437         } finally {
3438             if (resultOp == null || resultOp.isRight()) {
3439                 janusGraphDao.rollback();
3440             } else {
3441                 janusGraphDao.commit();
3442             }
3443             // unlock resource
3444             graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3445         }
3446     }
3447
3448     public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
3449                                                                                         String containerComponentId, String componentInstanceId,
3450                                                                                         String userId) {
3451         Map<String, ComponentInstance> resultMap = new HashMap<>();
3452         Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3453         if (getOrigComponent.isRight()) {
3454             log.error("Failed to get the original component information");
3455             return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3456         }
3457         Component origComponent = getOrigComponent.left().value();
3458         try {
3459             lockComponent(origComponent, "copyComponentInstance");
3460         } catch (ComponentException e) {
3461             log.error("destComponentInstance's data is {}", origComponent.toString());
3462             return Either.right(componentsUtils
3463                 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
3464                     origComponent.toString()));
3465         }
3466         boolean failed = false;
3467         ComponentInstance actionResponse = null;
3468         try {
3469             actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
3470         } catch (ComponentException e) {
3471             failed = true;
3472             // on failure of the create instance unlock the resource and rollback the transaction.
3473             return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3474         } finally {
3475             // on failure of the create instance unlock the resource and rollback the transaction.
3476             if (null == actionResponse) {
3477                 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
3478                 unlockComponent(failed, origComponent);
3479             }
3480         }
3481         Either<String, ResponseFormat> resultOp = null;
3482         try {
3483             ComponentInstance destComponentInstance = actionResponse;
3484             log.debug("destComponentInstance's data is {}", destComponentInstance);
3485             resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
3486             resultMap.put("componentInstance", destComponentInstance);
3487         } finally {
3488             // unlock resource
3489             if (resultOp == null || resultOp.isRight()) {
3490                 unlockComponent(true, origComponent);
3491                 janusGraphDao.rollback();
3492                 log.error("Failed to deep copy component instance");
3493             } else {
3494                 unlockComponent(false, origComponent);
3495                 janusGraphDao.commit();
3496                 log.debug("Success trasaction commit");
3497             }
3498         }
3499         if (resultOp == null || resultOp.isRight()) {
3500             return Either
3501                 .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
3502         } else {
3503             return Either.left(resultMap);
3504         }
3505     }
3506
3507     private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
3508                                                                      String sourceComponentInstanceId, ComponentInstance destComponentInstance,
3509                                                                      String userId) {
3510         Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3511         if (getDestComponent.isRight()) {
3512             log.error("Failed to get the dest component information");
3513             return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3514         }
3515         Component destComponent = getDestComponent.left().value();
3516         Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
3517             destComponent, sourceComponentInstanceId, destComponentInstance);
3518         if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
3519             log.error("Failed to copy component instance with properties and inputs as part of deep copy");
3520             return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
3521                 "Failed to copy the component instance with properties and inputs as part of deep copy"));
3522         }
3523         Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
3524             sourceComponentInstanceId, destComponentInstance, userId);
3525         if (copyComponentInstanceWithAttributes.isRight()) {
3526             log.error("Failed to copy component instance with attributes as part of deep copy");
3527             return Either.right(componentsUtils
3528                 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
3529         }
3530         return Either.left(COPY_COMPONENT_INSTANCE_OK);
3531     }
3532
3533     private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
3534                                                                                         String sourceComponentInstanceId,
3535                                                                                         ComponentInstance destComponentInstance) {
3536         log.debug("start to copy ComponentInstance with properties and inputs");
3537         List<ComponentInstanceProperty> sourcePropList = null;
3538         if (sourceComponent.getComponentInstancesProperties() != null
3539             && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
3540             sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
3541             log.debug("sourcePropList");
3542         }
3543         List<ComponentInstanceProperty> destPropList = null;
3544         String destComponentInstanceId = destComponentInstance.getUniqueId();
3545         log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
3546         if (destComponent.getComponentInstancesProperties() != null
3547             && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
3548             destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
3549             log.debug("destPropList {}");
3550         }
3551         List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
3552         if (null != destPropList && null != sourcePropList) {
3553             log.debug("start to set property and attribute");
3554             for (ComponentInstanceProperty destProp : destPropList) {
3555                 String destPropertyName = destProp.getName();
3556                 for (ComponentInstanceProperty sourceProp : sourcePropList) {
3557                     if (!destPropertyName.equals(sourceProp.getName())) {
3558                         continue;
3559                     }
3560                     log.debug("now set property");
3561                     final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
3562                     if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
3563                         .equals(sourceProp.getValue()))) {
3564                         log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
3565                         destProp.setValue(sourceProp.getValue());
3566                         Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
3567                             destComponentInstanceId, destProp);
3568                         if (updatePropertyValueEither.isRight()) {
3569                             log.error("Failed to copy the property {}", destPropertyName);
3570                             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3571                                 "Failed to paste component instance to the canvas, property copy"));
3572                         }
3573                         break;
3574                     }
3575                     log.debug("Now start to update inputs");
3576                     if (getInputValues != null) {
3577                         if (getInputValues.isEmpty()) {
3578                             log.debug("property is return from input, set by man");
3579                             break;
3580                         }
3581                         log.debug("Now starting to copy the {} property", destPropertyName);
3582                         Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
3583                             getInputValues.get(0).getInputId());
3584                         if (getSourceInputDefaultValue.isRight()) {
3585                             return Either.right(getSourceInputDefaultValue.right().value());
3586                         }
3587                         componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
3588                     }
3589                 }
3590             }
3591         }
3592         return Either.left(COPY_COMPONENT_INSTANCE_OK);
3593     }
3594
3595     private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
3596                                                                                String sourceComponentInstanceId,
3597                                                                                ComponentInstance destComponentInstance, String userId) {
3598         String destComponentInstanceId = destComponentInstance.getUniqueId();
3599         log.info("start to copy component instance with attributes");
3600         List<ComponentInstanceAttribute> sourceAttributeList = null;
3601         if (sourceComponent.getComponentInstancesAttributes() != null
3602             && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
3603             sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
3604             log.info("sourceAttributes {}");
3605         }
3606         List<ComponentInstanceAttribute> destAttributeList = null;
3607         if (destComponent.getComponentInstancesAttributes() != null
3608             && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
3609             destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
3610             log.info("destAttributeList {}");
3611         }
3612         if (null != sourceAttributeList && null != destAttributeList) {
3613             log.info("set attribute");
3614             for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
3615                 String sourceAttributeName = sourceAttribute.getName();
3616                 for (ComponentInstanceAttribute destAttribute : destAttributeList) {
3617                     if (sourceAttributeName.equals(destAttribute.getName())) {
3618                         log.debug("Start to copy the attribute exists {}", sourceAttributeName);
3619                         sourceAttribute.setUniqueId(
3620                             UniqueIdBuilder.buildResourceInstanceUniuqeId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
3621                         Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
3622                             ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
3623                         if (updateAttributeValueEither.isRight()) {
3624                             log.error("Failed to copy the attribute");
3625                             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3626                                 "Failed to paste component instance to the canvas, attribute copy"));
3627                         }
3628                         break;
3629                     }
3630                 }
3631             }
3632         }
3633         return Either.left(COPY_COMPONENT_INSTANCE_OK);
3634     }
3635
3636     private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
3637                                                                                                         String componentId, String resourceInstanceId,
3638                                                                                                         ComponentInstanceAttribute attribute,
3639                                                                                                         String userId) {
3640         Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
3641         validateUserExists(userId);
3642         if (componentTypeEnum == null) {
3643             BeEcompErrorManager.getInstance()
3644                 .logInvalidInputError("createOrUpdateAttributeValueForCopyPaste", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3645             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3646             return resultOp;
3647         }
3648         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3649         if (getResourceResult.isRight()) {
3650             log.info("Failed to retrieve component id {}", componentId);
3651             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3652             return resultOp;
3653         }
3654         Component containerComponent = getResourceResult.left().value();
3655         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3656         if (resourceInstanceStatus.isRight()) {
3657             resultOp = Either
3658                 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3659             return resultOp;
3660         }
3661         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3662         String propertyType = attribute.getType();
3663         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3664         log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3665         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3666             SchemaDefinition def = attribute.getSchema();
3667             if (def == null) {
3668                 log.info("Schema doesn't exists for attribute of type {}", type);
3669                 return Either
3670                     .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3671             }
3672             PropertyDataDefinition propDef = def.getProperty();
3673             if (propDef == null) {
3674                 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3675                 return Either
3676                     .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3677             }
3678         }
3679         List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
3680         Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
3681             .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3682         StorageOperationStatus status;
3683         if (instanceAttribute.isPresent()) {
3684             log.info("updateComponentInstanceAttribute");
3685             status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3686         } else {
3687             log.info("addComponentInstanceAttribute");
3688             status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3689         }
3690         if (status != StorageOperationStatus.OK) {
3691             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3692             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3693             return resultOp;
3694         }
3695         List<String> path = new ArrayList<>();
3696         path.add(foundResourceInstance.getUniqueId());
3697         attribute.setPath(path);
3698         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3699         Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3700             .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3701         if (updateContainerRes.isRight()) {
3702             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3703             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3704             return resultOp;
3705         }
3706         resultOp = Either.left(attribute);
3707         return resultOp;
3708     }
3709
3710     private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
3711                                                                            ComponentInstanceProperty property) {
3712         Either<String, ResponseFormat> resultOp;
3713         Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3714         if (getComponent.isRight()) {
3715             log.error("Failed to get the component information");
3716             return Either.right(componentsUtils
3717                 .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3718         }
3719         Component containerComponent = getComponent.left().value();
3720         StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3721         if (status != StorageOperationStatus.OK) {
3722             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3723             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3724             return resultOp;
3725         }
3726         Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3727             .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3728         if (updateContainerRes.isRight()) {
3729             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3730             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3731             return resultOp;
3732         }
3733         return Either.left("Update OK");
3734     }
3735
3736     private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3737         List<InputDefinition> inputList = component.getInputs();
3738         for (InputDefinition input : inputList) {
3739             if (input.getUniqueId().equals(inputId)) {
3740                 if (input.getDefaultValue() == null) {
3741                     log.debug("The input's default value is null");
3742                     return Either.left(null);
3743                 }
3744                 return Either.left(input.getDefaultValue());
3745             }
3746         }
3747         log.error("The input's default value with id {} is not found", inputId);
3748         return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3749     }
3750
3751     /**
3752      * Method to delete selected nodes and edges on composition page
3753      *
3754      * @param containerComponentType
3755      * @param componentId
3756      * @param componentInstanceIdList
3757      * @param userId
3758      * @return
3759      */
3760     public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
3761                                                                   List<String> componentInstanceIdList, String userId) {
3762         List<String> deleteErrorIds = new ArrayList<>();
3763         Map<String, List<String>> deleteErrorMap = new HashMap<>();
3764         validateUserExists(userId);
3765         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
3766             ComponentTypeEnum.findByParamName(containerComponentType), null);
3767         boolean failed = false;
3768         try {
3769             lockComponent(containerComponent, "batchDeleteComponentInstance");
3770             for (String eachInstanceId : componentInstanceIdList) {
3771                 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
3772                     eachInstanceId);
3773                 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3774                 if (actionResponse.isRight()) {
3775                     log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3776                     deleteErrorIds.add(eachInstanceId);
3777                 }
3778             }
3779             //sending the ids of the error nodes that were not deleted to UI
3780             deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3781             return deleteErrorMap;
3782         } catch (ComponentException e) {
3783             failed = true;
3784             throw e;
3785         } finally {
3786             unlockComponent(failed, containerComponent);
3787         }
3788     }
3789
3790     private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
3791                                                                                    String componentInstanceId) {
3792         ComponentInstance resultOp;
3793         final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3794         try {
3795             resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3796             log.info("Successfully deleted instance with id {}", componentInstanceId);
3797             return Either.left(resultOp);
3798         } catch (ComponentException e) {
3799             log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3800             return Either.right(new ResponseFormat());
3801         }
3802     }
3803
3804     public void validateUser(final String userId) {
3805         final User user = userValidations.validateUserExists(userId);
3806         userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
3807     }
3808
3809     public void setCompositionBusinessLogic(CompositionBusinessLogic compositionBusinessLogic) {
3810         this.compositionBusinessLogic = compositionBusinessLogic;
3811     }
3812
3813     public void setContainerInstanceTypesData(ContainerInstanceTypesData containerInstanceTypesData) {
3814         this.containerInstanceTypesData = containerInstanceTypesData;
3815     }
3816
3817 }