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