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