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