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