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