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