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