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