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