[SDC] rebase 1710 code
[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 java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Objects;
30 import java.util.Optional;
31 import java.util.UUID;
32 import java.util.stream.Collectors;
33
34 import org.apache.commons.collections.CollectionUtils;
35 import org.apache.commons.collections.MapUtils;
36 import org.apache.commons.lang.StringUtils;
37 import org.apache.commons.lang3.tuple.ImmutablePair;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
40 import org.openecomp.sdc.be.dao.api.ActionStatus;
41 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
42 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
43 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
44 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
48 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
51 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
52 import org.openecomp.sdc.be.model.ArtifactDefinition;
53 import org.openecomp.sdc.be.model.Component;
54 import org.openecomp.sdc.be.model.ComponentInstance;
55 import org.openecomp.sdc.be.model.ComponentInstanceInput;
56 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
57 import org.openecomp.sdc.be.model.ComponentParametersView;
58 import org.openecomp.sdc.be.model.DataTypeDefinition;
59 import org.openecomp.sdc.be.model.GroupDefinition;
60 import org.openecomp.sdc.be.model.GroupInstance;
61 import org.openecomp.sdc.be.model.InputDefinition;
62 import org.openecomp.sdc.be.model.LifecycleStateEnum;
63 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
64 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
65 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
66 import org.openecomp.sdc.be.model.Resource;
67 import org.openecomp.sdc.be.model.User;
68 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
69 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
70 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
71 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
72 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
73 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
74 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
75 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
76 import org.openecomp.sdc.be.resources.data.PropertyValueData;
77 import org.openecomp.sdc.be.tosca.ToscaUtils;
78 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
79 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
80 import org.openecomp.sdc.common.api.Constants;
81 import org.openecomp.sdc.common.datastructure.Wrapper;
82 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
83 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
84 import org.openecomp.sdc.common.util.ValidationUtils;
85 import org.openecomp.sdc.exception.ResponseFormat;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.springframework.beans.factory.annotation.Autowired;
89
90 import fj.data.Either;
91
92 public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
93
94         private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
95
96         @Autowired
97         private IComponentInstanceOperation componentInstanceOperation;
98
99         @Autowired
100         private ArtifactsBusinessLogic artifactBusinessLogic;
101         @Autowired
102         private ApplicationDataTypeCache dataTypeCache;
103         
104         public static final String VF_MODULE = "org.openecomp.groups.VfModule";
105
106         public ComponentInstanceBusinessLogic() {
107         }
108
109         public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
110                 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
111         }
112
113         public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
114
115                 Component origComponent = null;
116                 Either<ComponentInstance, ResponseFormat> resultOp = null;
117                 User user = null;
118                 org.openecomp.sdc.be.model.Component containerComponent = null;
119                 ComponentTypeEnum containerComponentType;
120                 
121                 try{
122                         Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
123                         if (resp.isRight()) {
124                                 return Either.right(resp.right().value());
125                         } else {
126                                 user = resp.left().value();
127                         }
128
129                         Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
130                         if (validateValidJson.isRight()) {
131                                 return Either.right(validateValidJson.right().value());
132                         }
133         
134                         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
135                         if (validateComponentType.isRight()) {
136                                 return Either.right(validateComponentType.right().value());
137                         } else {
138                                 containerComponentType = validateComponentType.left().value();
139                         }
140         
141                         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
142                         if (validateComponentExists.isRight()) {
143                                 return Either.right(validateComponentExists.right().value());
144                         } else {
145                                 containerComponent = validateComponentExists.left().value();
146                         }
147         
148                         if (ToscaUtils.isAtomicType(containerComponent)) {
149                                 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
150                                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
151                         }
152         
153                         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
154                         if (validateCanWorkOnComponent.isRight()) {
155                                 return Either.right(validateCanWorkOnComponent.right().value());
156                         }
157                         
158                         if (resourceInstance != null && containerComponentType != null) {
159                                 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
160                                 if (getOriginComponentRes.isRight()) {
161                                         return Either.right(getOriginComponentRes.right().value());
162                                 } else {
163                                         origComponent = getOriginComponentRes.left().value();
164                                 }
165                         }
166                         if (needLock) {
167                                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
168                                 if (lockComponent.isRight()) {
169                                         return Either.right(lockComponent.right().value());
170                                 }
171                         }
172                         log.debug("Try to create entry on graph");
173                         resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
174                         return resultOp;
175
176                 } finally {
177                         if (needLock)
178                                 unlockComponent(resultOp, containerComponent);
179                 }
180         }
181
182         public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
183
184                 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
185                 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
186                 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
187
188                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
189                 if (resp.isRight()) {
190                         return Either.right(resp.right().value());
191                 }
192
193                 User user = resp.left().value();
194                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
195                 if (validateComponentType.isRight()) {
196                         return Either.right(validateComponentType.right().value());
197                 }
198
199                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
200
201                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
202                 if (validateComponentExists.isRight()) {
203                         return Either.right(validateComponentExists.right().value());
204                 }
205                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
206
207                 if (ToscaUtils.isAtomicType(containerComponent)) {
208                         log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
209                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
210                 }
211
212                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
213                 if (validateCanWorkOnComponent.isRight()) {
214                         return Either.right(validateCanWorkOnComponent.right().value());
215                 }
216
217                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
218                 if (lockComponent.isRight()) {
219                         return Either.right(lockComponent.right().value());
220                 }
221
222                 try {
223                         log.debug("Try to create entry on graph");
224                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true);
225
226                         if (eitherResourceName.isRight()) {
227                                 resultOp = Either.right(eitherResourceName.right().value());
228                                 return resultOp;
229                         }
230                         Component origComponent = eitherResourceName.left().value();
231
232                         Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
233                         if (result.isRight()) {
234                                 log.debug("Failed to create resource instance {}", containerComponentId);
235                                 resultOp = Either.right(result.right().value());
236                                 return resultOp;
237
238                         }
239
240                         log.debug("Entity on graph is created.");
241                         ComponentInstance resResourceInfo = result.left().value();
242                         if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
243                                 associationInfo.setFromNode(resResourceInfo.getUniqueId());
244                         } else {
245                                 associationInfo.setToNode(resResourceInfo.getUniqueId());
246                         }
247
248                         RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
249                         Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
250                         if (resultReqCapDef.isLeft()) {
251                                 log.debug("Enty on graph is created.");
252                                 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
253                                 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
254                                 resultOp = Either.left(resInfo);
255                                 return resultOp;
256
257                         } else {
258                                 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
259                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
260                                 return resultOp;
261                         }
262
263                 } finally {
264                         unlockComponent(resultOp, containerComponent);
265                 }
266         }
267
268         private Either<Component, ResponseFormat> getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
269                 Either<Component, ResponseFormat> eitherResponse;
270                 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
271                 if (eitherComponent.isRight()) {
272                         log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName());
273                         eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
274                 } else {
275                         eitherResponse = Either.left(eitherComponent.left().value());
276                 }
277                 return eitherResponse;
278         }
279
280         private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
281                 Either<ComponentInstance, ResponseFormat> resultOp;
282
283                 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
284
285                 if (result.isRight()) {
286                         log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
287                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
288                         return resultOp;
289                 }
290
291                 log.debug("Entity on graph is created.");
292                 Component updatedComponent = result.left().value().getLeft();
293                 Map<String, String> existingEnvVersions = new HashMap<>();
294                 //TODO existingEnvVersions ??
295                 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
296                 if (addComponentInstanceArtifacts.isRight()) {
297                         log.debug("Failed to create component instance {}", componentInstance.getName());
298                         resultOp = Either.right(addComponentInstanceArtifacts.right().value());
299                         return resultOp;
300                 }
301
302                 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
303                 if (!updatedInstanceOptional.isPresent()) {
304                         log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
305                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
306                         return resultOp;
307                 }
308                 resultOp = Either.left(updatedInstanceOptional.get());
309                 return resultOp;
310         }
311
312         /**
313          * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
314          * 
315          * @param componentInstance
316          * @param userId
317          * @param existingEnvVersions
318          *            TODO
319          * @param containerComponentId
320          * 
321          * @return
322          */
323         protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user,
324                         Map<String, String> existingEnvVersions) {
325                 log.debug("add artifacts to resource instance");
326                 List<GroupDefinition> filteredGroups = null;
327                 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
328                 if (!ActionStatus.OK.equals(status)) {
329                         ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
330                         return Either.right(resultOp);
331                 }
332
333                 // generate heat_env if necessary
334                 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
335                 if (componentDeploymentArtifacts == null) {
336                         return Either.left(ActionStatus.OK);
337                 }
338                 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
339                 
340                 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
341                 
342                 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
343                         String type = artifact.getArtifactType();
344                         
345                         if ( !type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) ){
346                                 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
347                         }
348
349                         if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
350                                 continue;
351                         }
352
353                         if (artifact.checkEsIdExist()) {
354                                 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
355                                                 componentInstance.getName(), user, containerComponent, existingEnvVersions);
356                                 if (createHeatEnvPlaceHolder.isRight()) {
357                                         return Either.right(createHeatEnvPlaceHolder.right().value());
358                                 }
359                                 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
360                                 
361                                 //put env
362                                 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
363                                 
364                                 if(CollectionUtils.isNotEmpty(originComponent.getGroups())){
365                                         filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
366                                 }
367                                 if (CollectionUtils.isNotEmpty(filteredGroups)) {
368                                         for (GroupDefinition groupInstance : filteredGroups) {
369                                                 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
370                                                 if (op.isPresent()) {
371                                                         List<ArtifactDefinition> artifactsUid;
372                                                         if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
373                                                                 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
374                                                         } else {
375                                                                 artifactsUid = new ArrayList<>();
376                                                         }
377                                                         artifactsUid.add(artifactDefinition);
378                                                         groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
379                                                         break;
380                                                 }
381                                         }
382
383                                 }
384                         }
385                 }
386                 StorageOperationStatus artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
387                 if ( artStatus != StorageOperationStatus.OK){
388                         log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
389                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
390                         
391                 }
392                 StorageOperationStatus result = toscaOperationFacade
393                                 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
394                 if (result != StorageOperationStatus.OK) {
395                         log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
396                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
397                 }
398                 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
399                 return Either.left(ActionStatus.OK);
400         }
401
402         private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
403                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null);
404
405                 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
406                 if (getResourceDeploymentArtifacts.isRight()) {
407                         StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
408                         if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
409                                 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
410                                 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
411                         }
412                 } else {
413                         deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
414                 }
415
416                 if (!deploymentArtifacts.isEmpty()) {
417                         Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
418                         for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
419                                 if (!artifact.getValue().checkEsIdExist()) {
420                                         tempDeploymentArtifacts.remove(artifact.getKey());
421                                 }
422                         }
423
424                         resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
425                 }
426
427                 return ActionStatus.OK;
428         }
429
430         public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
431                 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
432         }
433
434         public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
435                         boolean needLock, boolean createNewTransaction) {
436
437                 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
438                 if (resp.isRight()) {
439                         return Either.right(resp.right().value());
440                 }
441
442                 Either<ComponentInstance, ResponseFormat> resultOp = null;
443
444                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
445                 if (validateComponentType.isRight()) {
446                         return Either.right(validateComponentType.right().value());
447                 }
448
449                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
450
451                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
452                 if (validateComponentExists.isRight()) {
453                         return Either.right(validateComponentExists.right().value());
454                 }
455                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
456
457                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
458                 if (validateCanWorkOnComponent.isRight()) {
459                         return Either.right(validateCanWorkOnComponent.right().value());
460                 }
461                 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
462                 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
463                 if (validateParentStatus.isRight()) {
464                         log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
465                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
466                         return resultOp;
467                 }
468                 if (!validateParentStatus.left().value()) {
469                         resultOp = Either.right(
470                                         componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
471                         return resultOp;
472                 }
473
474                 if (needLock) {
475                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
476                         if (lockComponent.isRight()) {
477                                 return Either.right(lockComponent.right().value());
478                         }
479                 }
480                 try {
481
482                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
483
484                         if (eitherResourceName.isRight()) {
485                                 resultOp = Either.right(eitherResourceName.right().value());
486                                 return resultOp;
487                         }
488                         Component origComponent = eitherResourceName.left().value();
489
490                         resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
491                         return resultOp;
492
493                 } finally {
494                         if (needLock)
495                                 unlockComponent(resultOp, containerComponent);
496                 }
497         }
498
499         // New Multiple Instance Update API
500         public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
501                         boolean createNewTransaction) {
502
503                 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
504                 org.openecomp.sdc.be.model.Component containerComponent = null;
505                 try {
506                         Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
507                         if (resp.isRight()) {
508                                 return Either.right(resp.right().value());
509                         }
510
511                         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
512                         if (validateComponentType.isRight()) {
513                                 return Either.right(validateComponentType.right().value());
514                         }
515
516                         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
517
518                         ComponentParametersView componentFilter = new ComponentParametersView();
519                         componentFilter.disableAll();
520                         componentFilter.setIgnoreUsers(false);
521                         componentFilter.setIgnoreComponentInstances(false);
522                         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true);
523                         if (validateComponentExists.isRight()) {
524                                 return Either.right(validateComponentExists.right().value());
525                         }
526
527                         containerComponent = validateComponentExists.left().value();
528
529                         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
530                         if (validateCanWorkOnComponent.isRight()) {
531                                 return Either.right(validateCanWorkOnComponent.right().value());
532                         }
533
534                         ComponentTypeEnum instanceType = getComponentType(containerComponentType);
535
536                         for (ComponentInstance componentInstance : componentInstanceList) {
537                                 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
538                                 if (!validateParent) {
539                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
540                                                         containerComponentId));
541                                         return resultOp;
542                                 }
543                         }
544
545                         if (needLock) {
546
547                                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
548                                 if (lockComponent.isRight()) {
549                                         return Either.right(lockComponent.right().value());
550                                 }
551                         }
552
553                         List<ComponentInstance> updatedList = new ArrayList<>();
554                         List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
555                         List<ComponentInstance> listForUpdate = new ArrayList<>();
556                         if(instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
557                                 containerComponent.setComponentInstances(componentInstanceList);
558                         else{
559                                 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
560                                 while(iterator.hasNext()){
561                                         ComponentInstance origInst = iterator.next();
562                                         Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
563                                         if(op.isPresent()){
564                                                 ComponentInstance updatedCi = op.get(); 
565                                                 updatedCi.setCustomizationUUID(origInst.getCustomizationUUID());
566                                                 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
567                                                 if(!isUniqueName){
568                                                         CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
569                                                                         origInst.getName(), updatedCi.getName());
570                                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
571                                                         return resultOp;
572                                                 }
573                                         
574                                                 listForUpdate.add(updatedCi);
575                                         }                                               
576                                         else
577                                                 listForUpdate.add(origInst);
578                                 }
579                                 containerComponent.setComponentInstances(listForUpdate);
580                         
581                                 if(resultOp == null){
582                                         Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
583                                         if(updateStatus.isRight()){
584                                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
585                                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
586                                                 return resultOp;
587                                         }
588                                         for(ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()){
589                                                 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
590                                                 if(op.isPresent()){
591                                                         updatedList.add(updatedInstance);
592                                                 }
593                                         }
594                                 }
595                         }
596
597                         resultOp = Either.left(updatedList);
598                         return resultOp;
599
600                 } finally {
601                         if (needLock) {
602                                 unlockComponent(resultOp, containerComponent);
603                         }
604                 }
605         }
606
607         private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
608                 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
609         }
610
611         private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
612                 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
613                         return ComponentTypeEnum.SERVICE_INSTANCE;
614                 } else {
615                         return ComponentTypeEnum.RESOURCE_INSTANCE;
616                 }
617         }
618
619         private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
620                         ComponentInstance componentInstance, boolean inTransaction) {
621
622                 Either<ComponentInstance, ResponseFormat> resultOp = null;
623                 Optional<ComponentInstance> componentInstanceOptional = null;
624                 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
625                 ComponentInstance oldComponentInstance = null;
626                 boolean isNameChanged = false;
627
628                 if (resultOp == null) {
629                         componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
630                         if (!componentInstanceOptional.isPresent()) {
631                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
632                                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
633                         }
634                 }
635                 if (resultOp == null) {
636                         oldComponentInstance = componentInstanceOptional.get();
637                         String newInstanceName = componentInstance.getName();
638                         if ( oldComponentInstance!=null && oldComponentInstance.getName() != null
639                                                                 && !oldComponentInstance.getName().equals( newInstanceName ) )
640                                 isNameChanged = true;
641                         Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
642                         if (!isUniqueName) {
643                                 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);
644                                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
645                         }
646                 }
647                 if (resultOp == null) {
648                         updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
649                         if (updateRes.isRight()) {
650                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
651                                                 updateRes.right().value());
652                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
653                         }else{
654                                 //region - Update instance Groups
655                                 if ( isNameChanged ){
656                                         Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance( containerComponent ,oldComponentInstance ,componentInstanceId );
657                                         if ( result.isRight() )
658                                                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId ,result.right().value() );
659                                 }
660                                 //endregion
661                         }
662                 }
663                 if (resultOp == null) {
664                         String newInstanceId = updateRes.left().value().getRight();
665                         Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
666
667                         if (!updatedInstanceOptional.isPresent()) {
668                                 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
669                                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
670                         }else{
671                                 resultOp = Either.left(updatedInstanceOptional.get());
672                         }
673                         
674                 }
675                 if (resultOp == null) {
676                         resultOp = Either.left(componentInstanceOptional.get());
677                 }
678                 return resultOp;
679         }
680         /**
681          * @param oldPrefix-  The normalized old vf name
682          * @param newNormailzedPrefix-  The normalized new vf name
683          * @param qualifiedGroupInstanceName-  old Group Instance Name
684          **/
685         //modify group names
686         private String getNewGroupName( String oldPrefix ,String newNormailzedPrefix , String qualifiedGroupInstanceName){
687                 if (qualifiedGroupInstanceName == null){
688                         log.info("CANNOT change group name ");
689                         return null;
690                 }
691                 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
692                         return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
693                 return qualifiedGroupInstanceName;
694         }
695
696         private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
697                 oldComponentInstance.setName(newComponentInstance.getName());
698                 oldComponentInstance.setModificationTime(System.currentTimeMillis());
699                 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
700                 if ( oldComponentInstance.getGroupInstances() != null )
701                         oldComponentInstance.getGroupInstances().forEach( group ->
702                                         group.setName( getNewGroupName( oldComponentInstance.getNormalizedName() , ValidationUtils.normalizeComponentInstanceName( newComponentInstance.getName() ) , group.getName() ) ) );
703                 return oldComponentInstance;
704         }
705
706         public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
707
708                 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
709                 if (resp.isRight()) {
710                         return Either.right(resp.right().value());
711                 }
712
713                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
714                 if (validateComponentType.isRight()) {
715                         return Either.right(validateComponentType.right().value());
716                 }
717
718                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
719                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
720                 if (validateComponentExists.isRight()) {
721                         return Either.right(validateComponentExists.right().value());
722                 }
723                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
724                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
725                 if (validateCanWorkOnComponent.isRight()) {
726                         return Either.right(validateCanWorkOnComponent.right().value());
727                 }
728
729                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
730                 if (lockComponent.isRight()) {
731                         return Either.right(lockComponent.right().value());
732                 }
733                 // validate resource
734                 /*
735                  * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
736                  * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
737                  * log.debug("Failed to lock service  {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
738                  */
739                 Either<ComponentInstance, ResponseFormat> resultOp = null;
740                 try {
741                         resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
742                         return resultOp;
743
744                 } finally {
745                         /*
746                          * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
747                          */
748                         unlockComponent(resultOp, containerComponent);
749                 }
750         }
751
752         private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
753
754                 Either<ComponentInstance, ResponseFormat> resultOp = null;
755                 ComponentInstance deletedInstance = null;
756                 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
757
758                 if (deleteRes.isRight()) {
759                         log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
760                         ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
761                         resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
762                 }
763                 if (resultOp == null) {
764                         log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
765                         deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
766                         resultOp = Either.left(deletedInstance);
767                 }
768                 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
769                         List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
770                         for(GroupDataDefinition currGroup : containerComponent.getGroups()){
771                                 if(currGroup.getMembers().containsKey(deletedInstance.getName())){
772                                         currGroup.getMembers().remove(deletedInstance.getName());
773                                         groupsToUpdate.add(currGroup);
774                                 }
775                         }
776                         Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = 
777                                         toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate);
778                         if (updateGroupsRes.isRight()) {
779                                 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
780                                 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
781                                 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
782                         }
783                 }
784                 if(resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())){
785                         List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
786                         if(CollectionUtils.isNotEmpty(inputsToDelete)){
787                                 StorageOperationStatus deleteInputsRes =
788                                                 toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
789                                 if(deleteInputsRes != StorageOperationStatus.OK){
790                                         log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
791                                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
792                                 }
793                         }
794                 }
795                 return resultOp;
796         }
797
798         private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
799                 ComponentInstance foundInstance = null;
800                 for(ComponentInstance instance : containerComponent.getComponentInstances()){
801                         if(instance.getUniqueId().equals(componentInstanceId)){
802                                 foundInstance = instance;
803                                 containerComponent.getComponentInstances().remove(instance);
804                                 break;
805                         }
806                 }
807                 return foundInstance;
808         }
809
810         public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
811                 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
812         }
813
814         public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
815                         boolean createNewTransaction) {
816
817                 Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
818                 if (resp.isRight()) {
819                         return Either.right(resp.right().value());
820                 }
821
822                 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
823
824                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
825                 if (validateComponentExists.isRight()) {
826                         return Either.right(validateComponentExists.right().value());
827                 }
828                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
829
830                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
831                 if (validateCanWorkOnComponent.isRight()) {
832                         return Either.right(validateCanWorkOnComponent.right().value());
833                 }
834                 if (needLock) {
835                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
836
837                         if (lockComponent.isRight()) {
838                                 return Either.right(lockComponent.right().value());
839                         }
840                 }
841
842                 try {
843
844                         resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
845
846                         return resultOp;
847
848                 } finally {
849                         if (needLock)
850                                 unlockComponent(resultOp, containerComponent);
851                 }
852         }
853
854         public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
855
856                 log.debug("Try to create entry on graph");
857                 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
858
859                 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
860
861                 if (result.isLeft()) {
862                         log.debug("Enty on graph is created.");
863                         RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
864                         resultOp = Either.left(requirementCapabilityRelDef);
865                         return resultOp;
866
867                 } else {
868                         log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
869                         String fromNameOrId = "";
870                         String toNameOrId = "";
871                         Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
872                         Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
873
874                         toNameOrId = requirementDef.getFromNode();
875                         fromNameOrId = requirementDef.getFromNode();
876                         if (fromResult.isLeft()) {
877                                 fromNameOrId = fromResult.left().value().getName();
878                         }
879                         if (toResult.isLeft()) {
880                                 toNameOrId = toResult.left().value().getName();
881                         }
882
883                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
884
885                         return resultOp;
886                 }
887
888         }
889
890         public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
891                 Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
892                 if (resp.isRight()) {
893                         return Either.right(resp.right().value());
894                 }
895
896                 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
897                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
898                 if (validateComponentExists.isRight()) {
899                         return Either.right(validateComponentExists.right().value());
900                 }
901                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
902
903                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
904                 if (validateCanWorkOnComponent.isRight()) {
905                         return Either.right(validateCanWorkOnComponent.right().value());
906                 }
907                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
908
909                 if (lockComponent.isRight()) {
910                         return Either.right(lockComponent.right().value());
911                 }
912                 try {
913                         log.debug("Try to create entry on graph");
914                         Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
915                         if (result.isLeft()) {
916                                 log.debug("Enty on graph is created.");
917                                 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
918                                 resultOp = Either.left(requirementCapabilityRelDef);
919                                 return resultOp;
920
921                         } else {
922
923                                 log.debug("Failed to dissocaite node  {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
924                                 String fromNameOrId = "";
925                                 String toNameOrId = "";
926                                 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
927                                 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
928
929                                 toNameOrId = requirementDef.getFromNode();
930                                 fromNameOrId = requirementDef.getFromNode();
931                                 if (fromResult.isLeft()) {
932                                         fromNameOrId = fromResult.left().value().getName();
933                                 }
934                                 if (toResult.isLeft()) {
935                                         toNameOrId = toResult.left().value().getName();
936                                 }
937
938                                 resultOp = Either
939                                                 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
940                                 return resultOp;
941                         }
942                 } finally {
943                         unlockComponent(resultOp, containerComponent);
944                 }
945         }
946
947         private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
948                 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
949                 Either<ComponentInstanceProperty, ResponseFormat> result;
950                 if (eitherAttribute.isLeft()) {
951                         log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
952                         ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
953
954                         result = Either.left(instanceAttribute);
955
956                 } else {
957                         log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
958
959                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
960
961                         result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
962
963                 }
964                 return result;
965         }
966
967         private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
968
969                 Either<ComponentInstanceProperty, ResponseFormat> result;
970
971                 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
972                 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
973                 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
974
975                 if (!errorWrapper.isEmpty()) {
976                         result = Either.right(errorWrapper.getInnerElement());
977                 } else {
978                         Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
979                         if (eitherAttribute.isLeft()) {
980                                 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
981                                 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
982                                 result = Either.left(instanceAttribute);
983
984                         } else {
985                                 log.debug("Failed to add attribute value {}  to resource instance {}", attribute, resourceInstanceId);
986
987                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
988                                 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
989
990                         }
991                 }
992                 return result;
993         }
994
995         /**
996          * Create Or Updates Attribute Instance
997          * 
998          * @param componentTypeEnum
999          * @param componentId
1000          * @param resourceInstanceId
1001          * @param attribute
1002          * @param userId
1003          * @return
1004          */
1005         public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1006                 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1007                 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1008
1009                 validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
1010                 if (errorWrapper.isEmpty()) {
1011                         validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1012                 }
1013                 if (errorWrapper.isEmpty()) {
1014                         validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1015                 }
1016                 if (errorWrapper.isEmpty()) {
1017                         validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1018                 }
1019
1020                 try {
1021                         if (errorWrapper.isEmpty()) {
1022                                 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1023                                 if (isCreate) {
1024                                         result = createAttributeValue(attribute, resourceInstanceId);
1025                                 } else {
1026                                         result = updateAttributeValue(attribute, resourceInstanceId);
1027                                 }
1028                         } else {
1029                                 result = Either.right(errorWrapper.getInnerElement());
1030                         }
1031                         return result;
1032                 }
1033
1034                 finally {
1035                         if (result == null || result.isRight()) {
1036                                 titanDao.rollback();
1037                         } else {
1038                                 titanDao.commit();
1039                         }
1040                         // unlock resource
1041                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1042                 }
1043         }
1044
1045         // US833308 VLI in service - specific network_role property value logic
1046         private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
1047                 if (StringUtils.isNotEmpty(property.getValue()) && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName()) && ComponentTypeEnum.SERVICE == componentTypeEnum) {
1048                         ComponentParametersView componentParametersView = new ComponentParametersView();
1049                         componentParametersView.disableAll();
1050                         componentParametersView.setIgnoreComponentInstances(false);
1051                         Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1052                         if (getServiceResult.isRight()) {
1053                                 return getServiceResult.right().value();
1054                         }
1055                         Component service = getServiceResult.left().value();
1056                         Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1057                         if (!getInstance.isPresent()) {
1058                                 return StorageOperationStatus.NOT_FOUND;
1059                         }
1060                         String prefix = service.getSystemName() + ".";
1061                         String value = property.getValue();
1062                         if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1063                                 property.setValue(prefix + value);
1064                         }
1065                 }
1066                 return StorageOperationStatus.OK;
1067         }
1068
1069         public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
1070
1071                 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1072
1073                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1074                 if (resp.isRight()) {
1075                         return Either.right(resp.right().value());
1076                 }
1077
1078                 if (componentTypeEnum == null) {
1079                         BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1080                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1081                         return resultOp;
1082                 }
1083                 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1084
1085                 if (getResourceResult.isRight()) {
1086                         log.debug("Failed to retrieve component, component id {}", componentId);
1087                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1088                         return resultOp;
1089                 }
1090                 Component containerComponent = getResourceResult.left().value();
1091
1092                 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1093                         log.info("Restricted operation for user: {} on service {}", userId, componentId);
1094                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1095                         return resultOp;
1096                 }
1097                 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1098                 if (resourceInstanceStatus.isRight()) {
1099                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1100                         return resultOp;
1101                 }
1102                 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1103                 // specific property value logic US833308
1104                 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property);
1105                 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1106                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1107                         return resultOp;
1108                 }
1109                 // lock resource
1110                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1111                 if (lockStatus != StorageOperationStatus.OK) {
1112                         log.debug("Failed to lock service {}", componentId);
1113                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1114                         return resultOp;
1115                 }
1116                 String innerType = null;
1117                 String propertyType = property.getType();
1118                 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1119                 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1120
1121                 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1122                         SchemaDefinition def = property.getSchema();
1123                         if (def == null) {
1124                                 log.debug("Schema doesn't exists for property of type {}", type);
1125                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1126                         }
1127                         PropertyDataDefinition propDef = def.getProperty();
1128                         if (propDef == null) {
1129                                 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1130                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1131                         }
1132                         innerType = propDef.getType();
1133                 }
1134                 // Specific Update Logic
1135                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1136                 if (allDataTypes.isRight()) {
1137                         TitanOperationStatus status = allDataTypes.right().value();
1138                         BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1139                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1140                 }
1141                 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1142
1143                 String newValue = property.getValue();
1144                 if (isValid.isRight()) {
1145                         Boolean res = isValid.right().value();
1146                         if (res == false) {
1147                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1148                         }
1149                 } else {
1150                         Object object = isValid.left().value();
1151                         if (object != null) {
1152                                 newValue = object.toString();
1153                         }
1154                 }               
1155
1156                 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true);
1157                 if (pair.getRight() != null && pair.getRight() == false) {
1158                         BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1159                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1160                 }
1161
1162                 try {
1163                         List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId);
1164                         Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1165                         StorageOperationStatus status;
1166                         instanceProperty.get().setValue(newValue);
1167                         if(instanceProperty.isPresent()){                               
1168                                 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1169                         } else {
1170                                 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1171                         }
1172                         if(status != StorageOperationStatus.OK){
1173                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1174                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1175                                 return resultOp;
1176                         }
1177                         List<String> path = new ArrayList<>();
1178                         path.add(foundResourceInstance.getUniqueId());
1179                         property.setPath(path);
1180                         
1181                         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1182                         Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1183                         
1184                         if (updateContainerRes.isRight()) {
1185                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1186                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1187                                 return resultOp;
1188                         }
1189                 resultOp = Either.left(property);
1190                 return resultOp;
1191
1192                 } finally {
1193                         if (resultOp == null || resultOp.isRight()) {
1194                                 titanDao.rollback();
1195                         } else {
1196                                 titanDao.commit();
1197                         }
1198                         // unlock resource
1199                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1200                 }
1201
1202         }
1203         
1204         public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) {
1205
1206                 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1207
1208                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1209                 if (resp.isRight()) {
1210                         return Either.right(resp.right().value());
1211                 }
1212
1213                 if (componentTypeEnum == null) {
1214                         BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1215                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1216                         return resultOp;
1217                 }
1218                 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1219
1220                 if (getResourceResult.isRight()) {
1221                         log.debug("Failed to retrieve component, component id {}", componentId);
1222                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1223                         return resultOp;
1224                 }
1225                 Component containerComponent = getResourceResult.left().value();
1226
1227                 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1228                         log.info("Restricted operation for user: {} on service {}", userId, componentId);
1229                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1230                         return resultOp;
1231                 }
1232                 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1233                 if (resourceInstanceStatus.isRight()) {
1234                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1235                         return resultOp;
1236                 }
1237                 
1238                 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1239         
1240                 // lock resource
1241                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1242                 if (lockStatus != StorageOperationStatus.OK) {
1243                         log.debug("Failed to lock service {}", componentId);
1244                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1245                         return resultOp;
1246                 }
1247                 String innerType = null;
1248                 String propertyType = property.getType();
1249                 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1250                 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1251
1252                 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1253                         SchemaDefinition def = property.getSchema();
1254                         if (def == null) {
1255                                 log.debug("Schema doesn't exists for property of type {}", type);
1256                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1257                         }
1258                         PropertyDataDefinition propDef = def.getProperty();
1259                         if (propDef == null) {
1260                                 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1261                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1262                         }
1263                         innerType = propDef.getType();
1264                 }
1265                 // Specific Update Logic
1266                 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
1267                 if (allDataTypes.isRight()) {
1268                         TitanOperationStatus status = allDataTypes.right().value();
1269                         BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1270                         return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1271                 }
1272                 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
1273
1274                 String newValue = property.getValue();
1275                 if (isValid.isRight()) {
1276                         Boolean res = isValid.right().value();
1277                         if (res == false) {
1278                                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1279                         }
1280                 } else {
1281                         Object object = isValid.left().value();
1282                         if (object != null) {
1283                                 newValue = object.toString();
1284                         }
1285                 }       
1286
1287                 try {
1288                         List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId);
1289                         Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1290                         StorageOperationStatus status;
1291                         if(instanceProperty.isPresent()){
1292                                 instanceProperty.get().setValue(property.getValue());
1293                                 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1294                         } else {
1295                                 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
1296                         }
1297                         if(status != StorageOperationStatus.OK){
1298                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1299                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1300                                 return resultOp;
1301                         }
1302                         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1303                         Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1304                         
1305                         if (updateContainerRes.isRight()) {
1306                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1307                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1308                                 return resultOp;
1309                         }
1310                 resultOp = Either.left(property);
1311                 return resultOp;
1312
1313                 } finally {
1314                         if (resultOp == null || resultOp.isRight()) {
1315                                 titanDao.rollback();
1316                         } else {
1317                                 titanDao.commit();
1318                         }
1319                         // unlock resource
1320                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1321                 }
1322
1323         }
1324
1325         public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1326                         String userId) {
1327
1328                 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1329
1330                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1331                 if (resp.isRight()) {
1332                         return Either.right(resp.right().value());
1333                 }
1334
1335                 if (componentTypeEnum == null) {
1336                         BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1337                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1338                         return resultOp;
1339                 }
1340
1341                 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1342                         log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1343                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1344                         return resultOp;
1345                 }
1346                 // lock resource
1347                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1348                 if (lockStatus != StorageOperationStatus.OK) {
1349                         log.debug("Failed to lock service {}", componentId);
1350                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1351                         return resultOp;
1352                 }
1353                 try {
1354                         String propertyValueUid = property.getValueUniqueUid();
1355
1356                         if (propertyValueUid == null) {
1357
1358                                 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1359
1360                                 if (counterRes.isRight()) {
1361                                         log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1362                                         StorageOperationStatus status = counterRes.right().value();
1363                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1364                                         resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1365                                 }
1366                                 Integer index = counterRes.left().value();
1367                                 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1368
1369                                 if (result.isLeft()) {
1370                                         log.trace("Property value was added to resource instance {}", resourceInstanceId);
1371                                         ComponentInstanceProperty instanceProperty = result.left().value();
1372
1373                                         resultOp = Either.left(instanceProperty);
1374
1375                                 } else {
1376                                         log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1377
1378                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1379
1380                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1381                                 }
1382
1383                         } else {
1384                                 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1385
1386                                 if (result.isLeft()) {
1387                                         log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1388                                         ComponentInstanceProperty instanceProperty = result.left().value();
1389
1390                                         resultOp = Either.left(instanceProperty);
1391
1392                                 } else {
1393                                         log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1394
1395                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1396
1397                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1398                                 }
1399                         }
1400                         if (resultOp.isLeft()) {
1401                                 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1402                                 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1403                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1404
1405                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1406
1407                                 }
1408                         }
1409                         return resultOp;
1410
1411                 } finally {
1412                         if (resultOp == null || resultOp.isRight()) {
1413                                 titanDao.rollback();
1414                         } else {
1415                                 titanDao.commit();
1416                         }
1417                         // unlock resource
1418                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1419                 }
1420
1421         }
1422
1423         public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1424
1425                 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1426
1427                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
1428                 if (resp.isRight()) {
1429                         return Either.right(resp.right().value());
1430                 }
1431
1432                 if (componentTypeEnum == null) {
1433                         BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1434                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1435                         return resultOp;
1436                 }
1437
1438                 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1439                         log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1440                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1441                         return resultOp;
1442                 }
1443                 // lock resource
1444                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1445                 if (lockStatus != StorageOperationStatus.OK) {
1446                         log.debug("Failed to lock service {}", componentId);
1447                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1448                         return resultOp;
1449                 }
1450                 try {
1451                         String propertyValueUid = inputProperty.getValueUniqueUid();
1452                         if (propertyValueUid == null) {
1453
1454                                 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1455
1456                                 if (counterRes.isRight()) {
1457                                         log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1458                                         StorageOperationStatus status = counterRes.right().value();
1459                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1460                                         resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1461                                 }
1462                                 Integer index = counterRes.left().value();
1463                                 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1464
1465                                 if (result.isLeft()) {
1466                                         log.debug("Property value was added to resource instance {}", resourceInstanceId);
1467                                         ComponentInstanceInput instanceProperty = result.left().value();
1468
1469                                         resultOp = Either.left(instanceProperty);
1470                                         return resultOp;
1471
1472                                 } else {
1473                                         log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1474
1475                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1476
1477                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1478
1479                                         return resultOp;
1480                                 }
1481
1482                         } else {
1483                                 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1484
1485                                 if (result.isLeft()) {
1486                                         log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1487                                         ComponentInstanceInput instanceProperty = result.left().value();
1488
1489                                         resultOp = Either.left(instanceProperty);
1490                                         return resultOp;
1491
1492                                 } else {
1493                                         log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1494
1495                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1496
1497                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1498
1499                                         return resultOp;
1500                                 }
1501                         }
1502
1503                 } finally {
1504                         if (resultOp == null || resultOp.isRight()) {
1505                                 titanDao.rollback();
1506                         } else {
1507                                 titanDao.commit();
1508                         }
1509                         // unlock resource
1510                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1511                 }
1512
1513         }
1514
1515         public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1516
1517                 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
1518                 if (resp.isRight()) {
1519                         return Either.right(resp.right().value());
1520                 }
1521
1522                 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1523
1524                 if (componentTypeEnum == null) {
1525                         BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1526                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1527                         return resultOp;
1528                 }
1529
1530                 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1531                         log.info("Restricted operation for user {} on service {}", userId, serviceId);
1532                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1533                         return resultOp;
1534                 }
1535                 // lock resource
1536                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1537                 if (lockStatus != StorageOperationStatus.OK) {
1538                         log.debug("Failed to lock service {}", serviceId);
1539                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1540                         return resultOp;
1541                 }
1542                 try {
1543                         Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1544
1545                         if (result.isLeft()) {
1546                                 log.debug("Property value {} was removed from graph.", propertyValueId);
1547                                 ComponentInstanceProperty instanceProperty = result.left().value();
1548
1549                                 resultOp = Either.left(instanceProperty);
1550                                 return resultOp;
1551
1552                         } else {
1553                                 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1554
1555                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1556
1557                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1558
1559                                 return resultOp;
1560                         }
1561
1562                 } finally {
1563                         if (resultOp == null || resultOp.isRight()) {
1564                                 titanDao.rollback();
1565                         } else {
1566                                 titanDao.commit();
1567                         }
1568                         // unlock resource
1569                         graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1570                 }
1571
1572         }
1573
1574         private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1575                 
1576                 Either<Component, ResponseFormat> eitherResponse = null;
1577                 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1578                 Component component;
1579                 ResponseFormat errorResponse;
1580                 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1581                 if (getComponentRes.isRight()) {
1582                         log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1583                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1584                         errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1585                         eitherResponse = Either.right(errorResponse);
1586                 }
1587                 if(eitherResponse == null) {
1588                         component = getComponentRes.left().value();
1589                         LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1590                         if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1591                                 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1592                                 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1593                                 eitherResponse =  Either.right(errorResponse);
1594                         }
1595                 }
1596                 if(eitherResponse == null) {
1597                         eitherResponse = Either.left(getComponentRes.left().value());
1598                 }
1599                 return eitherResponse;
1600         }
1601
1602         public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
1603
1604                 Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
1605                 if (resp.isRight()) {
1606                         return Either.right(resp.right().value());
1607                 }
1608
1609                 User user = resp.left().value();
1610                 Either<ComponentInstance, ResponseFormat> resultOp = null;
1611
1612                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1613                 if (validateComponentType.isRight()) {
1614                         return Either.right(validateComponentType.right().value());
1615                 }
1616
1617                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1618
1619                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
1620                 if (validateComponentExists.isRight()) {
1621                         return Either.right(validateComponentExists.right().value());
1622                 }
1623                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1624
1625                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1626                 if (validateCanWorkOnComponent.isRight()) {
1627                         return Either.right(validateCanWorkOnComponent.right().value());
1628                 }
1629
1630                 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,componentInstanceId);
1631                 if (resourceInstanceStatus.isRight()) {
1632                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
1633                         return resultOp;
1634                 }
1635
1636                 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
1637
1638                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
1639                 if (lockComponent.isRight()) {
1640                         return Either.right(lockComponent.right().value());
1641                 }
1642
1643                 try {
1644                         if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
1645                                 resultOp = Either.left(currentResourceInstance);
1646                                 return resultOp;
1647
1648                         }
1649                         String resourceId = newComponentInstance.getComponentUid();
1650                         Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
1651                         if(componentExistsRes.isRight()){
1652                                 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
1653                                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
1654                                 return resultOp;
1655                         }
1656                         else if (!componentExistsRes.left().value()) {
1657                                 log.debug("The resource {} not found ", resourceId);
1658                                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
1659                                 return resultOp;
1660                         }
1661
1662                 //      List<GroupInstance> groupInstances = currentResourceInstance.getGroupInstances();
1663                         Map<String, ArtifactDefinition> deploymentArtifacts =  currentResourceInstance.getDeploymentArtifacts();
1664                         resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1665                         if (resultOp.isRight()) {
1666                                 log.debug("failed to delete resource instance {}", resourceId);
1667                                 return resultOp;
1668                         }
1669
1670                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true);
1671
1672                         if (eitherResourceName.isRight()) {
1673                                 resultOp = Either.right(eitherResourceName.right().value());
1674                                 return resultOp;
1675                         }
1676
1677                         Component origComponent = eitherResourceName.left().value();
1678
1679                         ComponentInstance resResourceInfo = resultOp.left().value();
1680                         newComponentInstance.setName(resResourceInfo.getName());
1681                         newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
1682                         newComponentInstance.setPosX(resResourceInfo.getPosX());
1683                         newComponentInstance.setPosY(resResourceInfo.getPosY());
1684                         newComponentInstance.setDescription(resResourceInfo.getDescription());
1685                         newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition)origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName());
1686
1687                         resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
1688
1689                         if (resultOp.isRight()) {
1690                                 log.debug("failed to create resource instance {}", resourceId);
1691                                 return resultOp;
1692                         }
1693
1694                         ComponentInstance updatedComponentInstance = resultOp.left().value();
1695                         if (resultOp.isRight()) {
1696                                 log.debug("failed to create resource instance {}", resourceId);
1697                                 return resultOp;
1698                         }
1699
1700         /*              if (CollectionUtils.isNotEmpty(groupInstances)) {
1701                                 StorageOperationStatus addGroupsToComponentInstance = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, updatedComponentInstance, groupInstances);
1702                                 if (addGroupsToComponentInstance != StorageOperationStatus.OK) {
1703                                         BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1704                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1705                                         return resultOp;
1706                                 }
1707                         
1708                                 
1709                         }
1710                         if (MapUtils.isNotEmpty(deploymentArtifacts)) {
1711                                 StorageOperationStatus addDeploymentArtifactsToComponentInstance = toscaOperationFacade.addDeploymentArtifactsToComponentInstance(containerComponent, updatedComponentInstance, deploymentArtifacts);
1712                                 if (addDeploymentArtifactsToComponentInstance != StorageOperationStatus.OK) {
1713                                         BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1714                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1715                                         return resultOp;
1716                                 }
1717                         }*/
1718
1719                         
1720                         ComponentParametersView filter = new ComponentParametersView(true);
1721                         filter.setIgnoreComponentInstances(false);
1722                         Either<Component, StorageOperationStatus> updatedComponentRes  = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1723                         if (updatedComponentRes.isRight()) {
1724                                 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
1725                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
1726                                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1727                                 log.debug("Component with id {} was not found", containerComponentId);
1728                                 return Either.right(responseFormat);
1729                         }
1730                         resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),updatedComponentInstance.getUniqueId());
1731                         if (resourceInstanceStatus.isRight()) {
1732                                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
1733                                 return resultOp;
1734                         }
1735                         resultOp = Either.left(resourceInstanceStatus.left().value());
1736                         return resultOp;
1737
1738                 } finally {
1739                         unlockComponent(resultOp, containerComponent);
1740                 }
1741         }
1742
1743         protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
1744
1745         protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
1746
1747         // US831698
1748         public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
1749                 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
1750                 Component containerComponent = null;
1751
1752                 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1753                 try {
1754                         Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
1755                         if (validateUserExists.isRight()) {
1756                                 resultOp = Either.right(validateUserExists.right().value());
1757                                 return resultOp;
1758                         }
1759
1760                         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
1761                         if (validateComponentType.isRight()) {
1762                                 resultOp = Either.right(validateComponentType.right().value());
1763                                 return resultOp;
1764                         }
1765
1766                         Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
1767                         if (validateContainerComponentExists.isRight()) {
1768                                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
1769                                 return resultOp;
1770                         }
1771                         containerComponent = validateContainerComponentExists.left().value();
1772
1773                         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
1774                         if (resourceInstanceStatus.isRight()) {
1775                                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
1776                                 return resultOp;
1777                         }
1778                 
1779                         List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
1780                         if(CollectionUtils.isEmpty(instanceProperties)){
1781                                 instanceProperties = new ArrayList<>();
1782                         }
1783                         resultOp = Either.left(instanceProperties);
1784                         return resultOp;
1785                 } finally {
1786                         unlockComponent(resultOp, containerComponent);
1787                 }
1788         }
1789
1790         protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
1791                 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
1792
1793                 if (counterRes.isRight()) {
1794                         log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId);
1795                         StorageOperationStatus status = counterRes.right().value();
1796                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1797                         errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
1798                 } else {
1799                         instaceCounterWrapper.setInnerElement(counterRes.left().value());
1800                 }
1801
1802         }
1803
1804         /**
1805          * updates componentInstance modificationTime
1806          * 
1807          * @param componentInstance
1808          * @param componentInstanceType
1809          * @param modificationTime
1810          * @param inTransaction
1811          * @return
1812          */
1813         public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
1814                 Either<ComponentInstanceData, ResponseFormat> result;
1815                 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
1816                                 inTransaction);
1817                 if (updateComponentInstanceRes.isRight()) {
1818                         log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
1819                         result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
1820                 } else {
1821                         result = Either.left(updateComponentInstanceRes.left().value());
1822                 }
1823                 return result;
1824         }
1825
1826         private Boolean validateInstanceNameUniqueness(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
1827                 Boolean isUnique = true;
1828                 String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
1829                 if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
1830                         Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
1831                         if (foundComponentInstance.isPresent()) {
1832                                 isUnique = false;
1833                         }
1834                         if (isUnique) {
1835                                 foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().endsWith(newInstanceNormalizedName)).findFirst();
1836                                 if (foundComponentInstance.isPresent()) {
1837                                         isUnique = false;
1838                                 }
1839                         }
1840                 }
1841                 return isUnique;
1842         }
1843         
1844         private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
1845                 Boolean isUnique = true;
1846                 String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
1847                 if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
1848                         Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
1849                         if (foundComponentInstance.isPresent()) {
1850                                 isUnique = false;
1851                         }
1852                 }
1853                 return isUnique;
1854         }
1855
1856         private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
1857                 
1858                 Either<ComponentInstance, StorageOperationStatus> result = null;
1859                 List<ComponentInstance> instances = containerComponent.getComponentInstances();
1860                 Optional<ComponentInstance> foundInstance = null;
1861                 if(CollectionUtils.isEmpty(instances)){
1862                         result = Either.right(StorageOperationStatus.NOT_FOUND);
1863                 }
1864                 if(result == null){
1865                         foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1866                         if(!foundInstance.isPresent()){
1867                                 result = Either.right(StorageOperationStatus.NOT_FOUND);
1868                         }
1869                 }
1870                 if(result == null){
1871                         result = Either.left(foundInstance.get());
1872                 }
1873                 return result;
1874         }
1875 }