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