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