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