89ef6f7e199186fd42f86c02bee76377c5b17f72
[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.EnumMap;
25 import java.util.HashMap;
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.stream.Collectors;
31
32 import org.openecomp.sdc.be.config.BeEcompErrorManager;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
34 import org.openecomp.sdc.be.config.ConfigurationManager;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
37 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
38 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
39 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
40 import org.openecomp.sdc.be.model.ArtifactDefinition;
41 import org.openecomp.sdc.be.model.Component;
42 import org.openecomp.sdc.be.model.ComponentInstance;
43 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
44 import org.openecomp.sdc.be.model.ComponentInstanceInput;
45 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
46 import org.openecomp.sdc.be.model.ComponentParametersView;
47 import org.openecomp.sdc.be.model.HeatParameterDefinition;
48 import org.openecomp.sdc.be.model.LifecycleStateEnum;
49 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
50 import org.openecomp.sdc.be.model.Resource;
51 import org.openecomp.sdc.be.model.User;
52 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
53 import org.openecomp.sdc.be.model.operations.api.IComponentOperation;
54 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
55 import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
56 import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
57 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
58 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
59 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
60 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
61 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
62 import org.openecomp.sdc.common.api.Constants;
63 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
64 import org.openecomp.sdc.common.datastructure.Wrapper;
65 import org.openecomp.sdc.common.util.GeneralUtility;
66 import org.openecomp.sdc.common.util.ValidationUtils;
67 import org.openecomp.sdc.exception.ResponseFormat;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import org.springframework.beans.factory.annotation.Autowired;
71
72 import fj.data.Either;
73
74 public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
75
76         private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
77
78         static final String HEAT_ENV_NAME = "heatEnv";
79         private static final String HEAT_ENV_SUFFIX = "env";
80
81         private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
82
83         @Autowired
84         private IComponentInstanceOperation componentInstanceOperation;
85
86         @Autowired
87         private PropertyOperation propertyOperation;
88
89         @Autowired
90         private ArtifactsBusinessLogic artifactBusinessLogic;
91
92         @Autowired
93         private GroupOperation groupOperation;
94
95         public ComponentInstanceBusinessLogic() {
96         }
97
98         public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
99                 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true, true, true);
100         }
101
102         public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock,
103                         boolean createNewTransaction) {
104
105                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
106                 if (resp.isRight()) {
107                         return Either.right(resp.right().value());
108                 }
109
110                 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
111                 if (validateValidJson.isRight()) {
112                         return Either.right(validateValidJson.right().value());
113                 }
114
115                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
116                 if (validateComponentType.isRight()) {
117                         return Either.right(validateComponentType.right().value());
118                 }
119
120                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
121                 final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
122
123                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction);
124                 if (validateComponentExists.isRight()) {
125                         return Either.right(validateComponentExists.right().value());
126                 }
127                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
128
129                 Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
130                 if (validateAllowedToContainCompInstances.isRight()) {
131                         return Either.right(validateAllowedToContainCompInstances.right().value());
132                 }
133
134                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
135                 if (validateCanWorkOnComponent.isRight()) {
136                         return Either.right(validateCanWorkOnComponent.right().value());
137                 }
138                 if (resourceInstance != null && containerComponentType != null) {
139                         Either<Boolean, ResponseFormat> validateComponentInstanceParentState = validateComponentInstanceParentState(containerComponentType, resourceInstance);
140                         if (validateComponentInstanceParentState.isRight()) {
141                                 return Either.right(validateComponentInstanceParentState.right().value());
142                         }
143                 }
144                 if (needLock) {
145
146                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
147
148                         if (lockComponent.isRight()) {
149                                 return Either.right(lockComponent.right().value());
150                         }
151                 }
152
153                 Either<ComponentInstance, ResponseFormat> resultOp = null;
154                 try {
155                         log.debug("Try to create entry on graph");
156                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, inTransaction);
157
158                         if (eitherResourceName.isRight()) {
159                                 resultOp = Either.right(eitherResourceName.right().value());
160                                 return resultOp;
161                         }
162                         Component origComponent = eitherResourceName.left().value();
163
164                         resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, inTransaction);
165                         return resultOp;
166
167                 } finally {
168                         if (needLock)
169                                 unlockComponent(resultOp, containerComponent);
170                 }
171         }
172
173         public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
174
175                 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
176                 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
177                 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
178
179                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
180                 if (resp.isRight()) {
181                         return Either.right(resp.right().value());
182                 }
183
184                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
185                 if (validateComponentType.isRight()) {
186                         return Either.right(validateComponentType.right().value());
187                 }
188
189                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
190                 final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
191
192                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
193                 if (validateComponentExists.isRight()) {
194                         return Either.right(validateComponentExists.right().value());
195                 }
196                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
197
198                 Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
199                 if (validateAllowedToContainCompInstances.isRight()) {
200                         return Either.right(validateAllowedToContainCompInstances.right().value());
201                 }
202
203                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
204                 if (validateCanWorkOnComponent.isRight()) {
205                         return Either.right(validateCanWorkOnComponent.right().value());
206                 }
207
208                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
209                 if (lockComponent.isRight()) {
210                         return Either.right(lockComponent.right().value());
211                 }
212
213                 try {
214                         log.debug("Try to create entry on graph");
215                         NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
216                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(resourceInstance, true);
217
218                         if (eitherResourceName.isRight()) {
219                                 resultOp = Either.right(eitherResourceName.right().value());
220                                 return resultOp;
221                         }
222                         Component origComponent = eitherResourceName.left().value();
223
224                         Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, userId, containerOperation, true);
225                         if (result.isRight()) {
226                                 log.debug("Failed to create resource instance {}", containerComponentId);
227                                 resultOp = Either.right(result.right().value());
228                                 return resultOp;
229
230                         }
231
232                         log.debug("Entity on graph is created.");
233                         ComponentInstance resResourceInfo = result.left().value();
234                         if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
235                                 associationInfo.setFromNode(resResourceInfo.getUniqueId());
236                         } else {
237                                 associationInfo.setToNode(resResourceInfo.getUniqueId());
238                         }
239
240                         RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
241
242                         Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = componentInstanceOperation.associateResourceInstances(containerComponentId, containerNodeType, requirementCapabilityRelDef, true);
243                         if (resultReqCapDef.isLeft()) {
244                                 log.debug("Enty on graph is created.");
245                                 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
246                                 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
247                                 resultOp = Either.left(resInfo);
248                                 return resultOp;
249
250                         } else {
251                                 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
252                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
253                                 return resultOp;
254                         }
255
256                 } finally {
257                         unlockComponent(resultOp, containerComponent);
258                 }
259         }
260
261         private Either<Component, ResponseFormat> getOriginComponentNameFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
262                 Either<Component, ResponseFormat> eitherResponse;
263                 Either<Component, StorageOperationStatus> eitherComponent = getCompInstOriginComponentOperation().getComponent(componentInstance.getComponentUid(), inTransaction);
264                 if (eitherComponent.isRight()) {
265                         log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName());
266                         eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
267                 } else {
268                         eitherResponse = Either.left(eitherComponent.left().value());
269                 }
270                 return eitherResponse;
271         }
272
273         private Either<String, ResponseFormat> handleNameLogic(Component origComponent, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String containerComponentId, boolean isCreate, boolean inTransaction) {
274                 Either<String, ResponseFormat> eitherResult;
275                 final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
276
277                 Either<Integer, StorageOperationStatus> componentInNumberStatus = containerOperation.increaseAndGetComponentInstanceCounter(containerComponentId, true);
278
279                 if (componentInNumberStatus.isRight()) {
280                         log.debug("Failed to get component instance number for container component {} ", containerComponentId);
281                         eitherResult = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(componentInNumberStatus.right().value(), true), "", null));
282                 } else {
283                         String resourceInNumber = componentInNumberStatus.left().value().toString();
284                         eitherResult = Either.left(resourceInNumber);
285                 }
286
287                 if (eitherResult.isLeft()) {
288                         Either<Boolean, ResponseFormat> eitherSpecificLogic;
289                         if (isCreate) {
290                                 eitherSpecificLogic = handleNameLogicForNewComponentInstance(origComponent, componentInstance, eitherResult.left().value(), containerComponentType, inTransaction);
291                         } else {
292                                 eitherSpecificLogic = handleNameLogicForUpdatingComponentInstance(origComponent, componentInstance, componentInNumberStatus, containerComponentType, inTransaction);
293                         }
294                         if (eitherSpecificLogic.isRight()) {
295                                 eitherResult = Either.right(eitherSpecificLogic.right().value());
296                         }
297                 }
298                 return eitherResult;
299         }
300
301         private Either<Boolean, ResponseFormat> handleNameLogicForUpdatingComponentInstance(Component origComponent, ComponentInstance componentInstance, Either<Integer, StorageOperationStatus> componentInNumberStatus,
302                         ComponentTypeEnum containerComponentType, boolean inTransaction) {
303                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
304                 if (componentInstance.getName() == null || componentInstance.getName().isEmpty()) {
305                         if (origComponent == null) {
306                                 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
307
308                                 if (eitherResourceName.isRight()) {
309                                         eitherResult = Either.right(eitherResourceName.right().value());
310                                         return eitherResult;
311                                 }
312                                 origComponent = eitherResourceName.left().value();
313
314                                 String resourceName = origComponent.getName();
315                                 String logicalName = componentInstanceOperation.createComponentInstLogicalName(componentInNumberStatus.left().value().toString(), resourceName);
316                                 componentInstance.setName(logicalName);
317                                 if (containerComponentType == ComponentTypeEnum.RESOURCE) {
318                                         Resource resource = (Resource) origComponent;
319                                         componentInstance.setToscaComponentName(resource.getToscaResourceName());
320                                 }
321
322                         }
323                 }
324
325                 Either<Boolean, ResponseFormat> eitherValidation = validateComponentInstanceName(componentInstance.getName(), componentInstance, false);
326                 if (eitherValidation.isRight()) {
327                         eitherResult = Either.right(eitherValidation.right().value());
328                 }
329                 return eitherResult;
330         }
331
332         private Either<Boolean, ResponseFormat> handleNameLogicForNewComponentInstance(Component origComponent, ComponentInstance componentInstance, String resourceInNumber, ComponentTypeEnum containerComponentType, boolean inTransaction) {
333                 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
334
335                 if (origComponent == null) {
336                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
337
338                         if (eitherResourceName.isRight()) {
339                                 eitherResult = Either.right(eitherResourceName.right().value());
340                                 return eitherResult;
341                         }
342
343                         origComponent = eitherResourceName.left().value();
344                 }
345
346                 String resourceName = origComponent.getName();
347                 componentInstance.setComponentName(resourceName);
348                 if (componentInstance.getName() == null || componentInstance.getName().isEmpty())
349                         componentInstance.setName(resourceName);
350                 String logicalName = componentInstanceOperation.createComponentInstLogicalName(resourceInNumber, componentInstance.getName());
351
352                 Either<Boolean, ResponseFormat> eitherValidation = validateComponentInstanceName(logicalName, componentInstance, true);
353                 if (eitherValidation.isRight()) {
354                         eitherResult = Either.right(eitherValidation.right().value());
355                 }
356                 if (containerComponentType == ComponentTypeEnum.RESOURCE) {
357                         Resource resource = (Resource) origComponent;
358                         componentInstance.setToscaComponentName(resource.getToscaResourceName());
359                 }
360
361                 return eitherResult;
362         }
363
364         public Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId,
365                         boolean needLock, boolean inTransaction) {
366
367                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
368                 if (validateComponentType.isRight()) {
369                         return Either.right(validateComponentType.right().value());
370                 }
371
372                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
373                 final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
374                 Either<ComponentInstance, ResponseFormat> resultOp = null;
375                 if (needLock) {
376
377                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
378
379                         if (lockComponent.isRight()) {
380                                 return Either.right(lockComponent.right().value());
381                         }
382                 }
383                 try {
384                         resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, componentInstance, userId, containerOperation, inTransaction);
385                         return resultOp;
386
387                 } finally {
388                         if (needLock)
389                                 unlockComponent(resultOp, containerComponent);
390                 }
391
392         }
393
394         private Map<String, String> getExistingEnvVersions(ComponentInstance componentInstance) {
395                 if (null == componentInstance.getDeploymentArtifacts())
396                         return null;
397                 return componentInstance.getDeploymentArtifacts().values()
398                                 //filter env artifacts
399                                 .stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType()))
400                                 //map name to version 
401                                 .collect(Collectors.toMap(a -> a.getArtifactName(), a -> a.getArtifactVersion()));
402         }
403
404         private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component origComponent, ComponentInstance componentInstance, String userId,
405                         ComponentOperation containerOperation, boolean inTransaction) {
406                 Either<ComponentInstance, ResponseFormat> resultOp;
407                 boolean nameAlreadyExist = true;
408                 String resourceInNumber = "";
409                 String containerComponentId = containerComponent.getUniqueId();
410                 ComponentTypeEnum containerComponentType = containerComponent.getComponentType();
411                 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
412                 NodeTypeEnum compInstNodeType = getNodeTypeOfComponentInstanceOrigin();
413                 while (nameAlreadyExist) {
414
415                         Either<String, ResponseFormat> eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponent.getComponentType(), containerComponent.getUniqueId(), true, inTransaction);
416                         if (eitherNameLogic.isRight()) {
417                                 return Either.right(eitherNameLogic.right().value());
418                         } else {
419                                 resourceInNumber = eitherNameLogic.left().value();
420                         }
421
422                         Either<Boolean, StorageOperationStatus> isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, null, componentInstance.getNormalizedName());
423                         if (isNameExistStatus.isRight()) {
424                                 log.debug("Failed to check if component instance name exists for container component {}", containerComponentId);
425
426                                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId));
427                                 return resultOp;
428                         }
429                         nameAlreadyExist = isNameExistStatus.left().value();
430
431                 }
432
433                 Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.createComponentInstance(containerComponentId, containerNodeType, resourceInNumber, componentInstance, compInstNodeType, inTransaction);
434
435                 if (result.isRight()) {
436                         log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
437                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
438                         return resultOp;
439                 }
440
441                 log.debug("Entity on graph is created.");
442                 ComponentInstance compInst = result.left().value();
443
444                 Map<String, String> existingEnvVersions = getExistingEnvVersions(componentInstance);
445                 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(containerComponent, compInst, userId, inTransaction, existingEnvVersions);
446                 if (addComponentInstanceArtifacts.isRight()) {
447                         log.debug("Failed to create component instance {}", componentInstance.getName());
448                         resultOp = Either.right(addComponentInstanceArtifacts.right().value());
449                         return resultOp;
450                 }
451
452                 resultOp = Either.left(compInst);
453                 return resultOp;
454         }
455
456         /**
457          * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
458          * 
459          * @param componentInstance
460          * @param userId
461          * @param existingEnvVersions
462          * @param containerComponentId
463          * 
464          * @return
465          */
466         protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, String userId, boolean inTransaction,
467                         Map<String, String> existingEnvVersions) {
468                 log.debug("add artifacts to resource instance");
469
470                 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
471                 if (!ActionStatus.OK.equals(status)) {
472                         ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
473                         return Either.right(resultOp);
474                 }
475
476                 // generate heat_env if necessary
477                 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
478                 if (componentDeploymentArtifacts == null) {
479                         return Either.left(ActionStatus.OK);
480                 }
481                 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(componentDeploymentArtifacts);
482                 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
483                         // if (artifact.getArtifactType().equalsIgnoreCase(
484                         // ArtifactTypeEnum.HEAT.getType())) {
485                         String type = artifact.getArtifactType();
486
487                         if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
488                                 continue;
489                         }
490
491                         if (artifact.checkEsIdExist()) {
492                                 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
493                                 if (deploymentResourceArtifacts == null) {
494                                         log.debug("no deployment artifacts are configured for resource instance");
495                                         break;
496                                 }
497                                 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(HEAT_ENV_NAME);
498
499                                 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
500                                 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = artifactBusinessLogic.createArtifactPlaceHolderInfo(componentInstance.getUniqueId(), envLabel, placeHolderData, userId, ArtifactGroupTypeEnum.DEPLOYMENT,
501                                                 inTransaction);
502                                 if (createArtifactPlaceHolder.isRight()) {
503                                         return Either.right(createArtifactPlaceHolder.right().value());
504                                 }
505                                 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
506
507                                 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
508                                 artifactHeatEnv.setTimeout(0);
509                                 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
510
511                                 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
512                                 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
513                                 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = artifactBusinessLogic.addHeatEnvArtifact(artifactHeatEnv, artifact, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
514                                 if (addHeatEnvArtifact.isRight()) {
515                                         log.debug("failed to create heat env artifact on resource instance");
516                                         return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
517                                 }
518
519                                 ArtifactDefinition artifactDefinition = addHeatEnvArtifact.left().value();
520                                 if (artifact.getHeatParameters() != null) {
521                                         List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
522                                         for (HeatParameterDefinition parameter : artifact.getHeatParameters()) {
523                                                 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
524                                                 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
525                                                 heatEnvParameters.add(heatEnvParameter);
526                                         }
527                                         artifactDefinition.setHeatParameters(heatEnvParameters);
528                                 }
529                                 finalDeploymentArtifacts.put(envLabel, artifactDefinition);
530
531                                 // audit
532                                 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = artifactBusinessLogic.createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
533                                 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getName());
534                                 handleAuditing(AuditingActionEnum.ARTIFACT_UPLOAD, containerComponent, userId, artifactAuditingFields, inTransaction);
535                         }
536                         // }
537                 }
538                 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
539                 return Either.left(ActionStatus.OK);
540         }
541
542         private void handleAuditing(AuditingActionEnum artifactUpload, org.openecomp.sdc.be.model.Component containerComponent, String userId, EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields, boolean inTransaction) {
543
544                 Either<User, ActionStatus> user = userAdmin.getUser(userId, inTransaction);
545                 if (user.isRight()) {
546                         log.debug("failed to get user properties from graph for audit");
547                         return;
548                 }
549
550                 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user.left().value(), containerComponent, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, ComponentTypeEnum.RESOURCE_INSTANCE, artifactAuditingFields);
551
552         }
553
554         private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
555                 if (null != existingEnvVersions) {
556                         String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
557                         if (null != prevVersion) {
558                                 heatEnvArtifact.setArtifactVersion(prevVersion);
559                         }
560                 }
561         }
562
563         private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
564                 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
565                 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
566                 String fileName = heatArtifact.getArtifactName().replaceAll("." + heatExtension, "." + envExtension);
567                 heatEnvArtifact.setArtifactName(fileName);
568         }
569
570         private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
571                 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT);
572
573                 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
574                 if (getResourceDeploymentArtifacts.isRight()) {
575                         StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
576                         if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
577                                 log.debug("Failed to fetch resource artifacts. status is {}", status);
578                                 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
579                         }
580                 } else {
581                         deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
582                 }
583
584                 if (!deploymentArtifacts.isEmpty()) {
585                         Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
586                         for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
587                                 if (!artifact.getValue().checkEsIdExist()) {
588                                         tempDeploymentArtifacts.remove(artifact.getKey());
589                                 }
590                         }
591
592                         resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
593                 }
594
595                 return ActionStatus.OK;
596         }
597
598         public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
599                 return updateComponentInstance(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
600         }
601
602         public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
603                         boolean needLock, boolean createNewTransaction) {
604
605                 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
606                 if (resp.isRight()) {
607                         return Either.right(resp.right().value());
608                 }
609
610                 Either<ComponentInstance, ResponseFormat> resultOp = null;
611
612                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
613                 if (validateComponentType.isRight()) {
614                         return Either.right(validateComponentType.right().value());
615                 }
616
617                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
618
619                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, inTransaction, createNewTransaction);
620                 if (validateComponentExists.isRight()) {
621                         return Either.right(validateComponentExists.right().value());
622                 }
623                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
624
625                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
626                 if (validateCanWorkOnComponent.isRight()) {
627                         return Either.right(validateCanWorkOnComponent.right().value());
628                 }
629                 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
630                 Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, inTransaction);
631                 if (validateParentStatus.isRight()) {
632                         log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
633                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
634                         return resultOp;
635                 }
636                 Boolean isPrentValid = validateParentStatus.left().value();
637                 if (!isPrentValid) {
638                         resultOp = Either.right(
639                                         componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
640                         return resultOp;
641
642                 }
643
644                 if (needLock) {
645
646                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
647                         if (lockComponent.isRight()) {
648                                 return Either.right(lockComponent.right().value());
649                         }
650                 }
651
652                 try {
653
654                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, inTransaction);
655
656                         if (eitherResourceName.isRight()) {
657                                 resultOp = Either.right(eitherResourceName.right().value());
658                                 return resultOp;
659                         }
660                         Component origComponent = eitherResourceName.left().value();
661
662                         resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
663                         return resultOp;
664
665                 } finally {
666                         if (needLock)
667                                 unlockComponent(resultOp, containerComponent);
668                 }
669         }
670
671         // New Multiple Instance Update API
672         public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
673                         boolean createNewTransaction) {
674
675                 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
676                 org.openecomp.sdc.be.model.Component containerComponent = null;
677                 try {
678                         Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
679                         if (resp.isRight()) {
680                                 return Either.right(resp.right().value());
681                         }
682
683                         Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
684                         if (validateComponentType.isRight()) {
685                                 return Either.right(validateComponentType.right().value());
686                         }
687
688                         final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
689
690                         ComponentParametersView componentFilter = new ComponentParametersView();
691                         componentFilter.disableAll();
692                         componentFilter.setIgnoreUsers(false);
693                         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true);
694                         if (validateComponentExists.isRight()) {
695                                 return Either.right(validateComponentExists.right().value());
696                         }
697
698                         containerComponent = validateComponentExists.left().value();
699
700                         Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
701                         if (validateCanWorkOnComponent.isRight()) {
702                                 return Either.right(validateCanWorkOnComponent.right().value());
703                         }
704
705                         ComponentTypeEnum instanceType = getComponentType(containerComponentType);
706
707                         for (ComponentInstance componentInstance : componentInstanceList) {
708                                 Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstance.getUniqueId(), true);
709                                 if (validateParentStatus.isRight()) {
710                                         log.debug("Failed to get component instance {} on service {}", componentInstance.getUniqueId(), containerComponentId);
711                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
712                                         return resultOp;
713                                 }
714                                 Boolean isPrentValid = validateParentStatus.left().value();
715                                 if (!isPrentValid) {
716                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
717                                                         containerComponentId));
718                                         return resultOp;
719                                 }
720                         }
721
722                         if (needLock) {
723
724                                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
725                                 if (lockComponent.isRight()) {
726                                         return Either.right(lockComponent.right().value());
727                                 }
728                         }
729
730                         List<ComponentInstance> updatedList = new ArrayList<>();
731                         for (ComponentInstance componentInstance : componentInstanceList) {
732
733                                 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(componentInstance, true);
734
735                                 if (eitherResourceName.isRight()) {
736                                         resultOp = Either.right(eitherResourceName.right().value());
737                                         return resultOp;
738                                 }
739                                 Component origComponent = eitherResourceName.left().value();
740
741                                 Either<ComponentInstance, ResponseFormat> resultSingleUpdate = updateComponentInstance(containerComponentId, containerComponentType, origComponent, componentInstance.getUniqueId(), componentInstance, true);
742
743                                 if (resultSingleUpdate.isRight()) {
744                                         resultOp = Either.right(resultSingleUpdate.right().value());
745                                         return resultOp;
746                                 }
747                                 updatedList.add(resultSingleUpdate.left().value());
748                         }
749
750                         resultOp = Either.left(updatedList);
751                         return resultOp;
752
753                 } finally {
754                         if (needLock) {
755                                 unlockComponent(resultOp, containerComponent);
756                         }
757                 }
758         }
759
760         private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
761                 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
762                         return ComponentTypeEnum.SERVICE_INSTANCE;
763                 } else {
764                         return ComponentTypeEnum.RESOURCE_INSTANCE;
765                 }
766         }
767
768         public Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentParam, org.openecomp.sdc.be.model.Component containerComponent, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
769                         ComponentInstance componentInstance, boolean needLock, boolean inTransaction) {
770                 Either<ComponentInstance, ResponseFormat> resultOp = null;
771                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
772                 if (validateComponentType.isRight()) {
773                         return Either.right(validateComponentType.right().value());
774                 }
775
776                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
777                 if (needLock) {
778
779                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
780                         if (lockComponent.isRight()) {
781                                 return Either.right(lockComponent.right().value());
782                         }
783                 }
784
785                 try {
786
787                         resultOp = updateComponentInstance(containerComponent.getUniqueId(), containerComponentType, origComponent, componentInstanceId, componentInstance, inTransaction);
788                         return resultOp;
789
790                 } finally {
791                         if (needLock)
792                                 unlockComponent(resultOp, containerComponent);
793                 }
794
795         }
796
797         private Either<ComponentInstance, ResponseFormat> updateComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
798                         ComponentInstance componentInstance, boolean inTransaction) {
799                 Either<ComponentInstance, ResponseFormat> resultOp;
800
801                 Either<String, ResponseFormat> eitherNameLogic = handleNameLogic(origComponent, componentInstance, containerComponentType, containerComponentId, false, inTransaction);
802                 if (eitherNameLogic.isRight()) {
803                         return Either.right(eitherNameLogic.right().value());
804                 }
805                 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
806
807                 Either<Boolean, StorageOperationStatus> isNameExistStatus = componentInstanceOperation.isComponentInstanceNameExist(containerComponentId, containerNodeType, componentInstanceId, componentInstance.getNormalizedName());
808                 if (isNameExistStatus.isRight()) {
809                         log.debug("Failed to get resource instance names for service {}", containerComponentId);
810
811                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND, componentInstance.getName(), containerComponentId));
812                         return resultOp;
813                 }
814                 Boolean isNameExist = isNameExistStatus.left().value();
815                 if (isNameExist) {
816                         containerComponentType = getComponentTypeOfComponentInstance();
817                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
818                         return resultOp;
819
820                 }
821
822                 log.debug("Try to update entry on graph");
823                 Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.updateResourceInstance(containerComponentId, containerNodeType, componentInstanceId, componentInstance, inTransaction);
824
825                 if (result.isLeft()) {
826                         log.debug("Enty on graph is updated.");
827                         ComponentInstance resResourceInfo = result.left().value();
828                         resultOp = Either.left(resResourceInfo);
829                         return resultOp;
830
831                 } else {
832                         log.debug("Failed to update entry on graph for resource instance {}", componentInstance.getName());
833                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), false), "", componentInstance.getName()));
834                         return resultOp;
835                 }
836
837         }
838
839         public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String resourceInstanceId, String userId) {
840
841                 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
842                 if (resp.isRight()) {
843                         return Either.right(resp.right().value());
844                 }
845
846                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
847                 if (validateComponentType.isRight()) {
848                         return Either.right(validateComponentType.right().value());
849                 }
850
851                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
852                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
853                 if (validateComponentExists.isRight()) {
854                         return Either.right(validateComponentExists.right().value());
855                 }
856                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
857                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
858                 if (validateCanWorkOnComponent.isRight()) {
859                         return Either.right(validateCanWorkOnComponent.right().value());
860                 }
861
862                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
863                 if (lockComponent.isRight()) {
864                         return Either.right(lockComponent.right().value());
865                 }
866                 // validate resource
867                 /*
868                  * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user {} on service {}", userId, containerComponentId); return Either.right(componentsUtils
869                  * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
870                  * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
871                  */
872                 Either<ComponentInstance, ResponseFormat> resultOp = null;
873                 try {
874                         resultOp = deleteComponentInstance(containerComponentId, resourceInstanceId, containerComponentType);
875                         return resultOp;
876
877                 } finally {
878                         /*
879                          * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
880                          */
881                         unlockComponent(resultOp, containerComponent);
882                 }
883         }
884
885         private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentId, String resourceInstanceId, ComponentTypeEnum containerComponentType) {
886                 Either<ComponentInstance, ResponseFormat> resultOp;
887                 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
888                 Either<ComponentInstance, StorageOperationStatus> result = componentInstanceOperation.deleteComponentInstance(containerNodeType, containerComponentId, resourceInstanceId, true);
889
890                 if (result.isRight()) {
891                         log.debug("Failed to delete entry on graph for resourceInstance {}", resourceInstanceId);
892                         ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value(), containerComponentType);
893                         // TODO check
894                         /*
895                          * if (ActionStatus.SERVICE_NOT_FOUND.equals(status)) { resultOp = Either .right(componentsUtils .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND)); } else {
896                          */
897                         resultOp = Either.right(componentsUtils.getResponseFormat(status, resourceInstanceId));
898                         // }
899                         return resultOp;
900                 }
901                 ComponentInstance resResourceInfo = result.left().value();
902                 resultOp = Either.left(resResourceInfo);
903
904                 log.debug("Entry on graph is deleted. Exist more connections on this artifact.");
905
906                 Map<String, ArtifactDefinition> deploymentArtifacts = resResourceInfo.getDeploymentArtifacts();
907                 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
908                         StorageOperationStatus deleteArtifactsIfNotOnGraph = artifactBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(new ArrayList<ArtifactDefinition>(deploymentArtifacts.values()));
909                         if (!deleteArtifactsIfNotOnGraph.equals(StorageOperationStatus.OK)) {
910                                 log.debug("failed to delete artifact payload. status={}", deleteArtifactsIfNotOnGraph.name());
911                                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), resourceInstanceId));
912                         }
913
914                 }
915                 return resultOp;
916         }
917
918         public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
919                 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
920         }
921
922         public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
923                         boolean createNewTransaction) {
924
925                 Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
926                 if (resp.isRight()) {
927                         return Either.right(resp.right().value());
928                 }
929
930                 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
931
932                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, inTransaction, createNewTransaction);
933                 if (validateComponentExists.isRight()) {
934                         return Either.right(validateComponentExists.right().value());
935                 }
936                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
937
938                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
939                 if (validateCanWorkOnComponent.isRight()) {
940                         return Either.right(validateCanWorkOnComponent.right().value());
941                 }
942                 if (needLock) {
943                         Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
944
945                         if (lockComponent.isRight()) {
946                                 return Either.right(lockComponent.right().value());
947                         }
948                 }
949
950                 try {
951
952                         resultOp = associateRIToRIOnGraph(componentId, requirementDef, componentTypeEnum, inTransaction);
953
954                         return resultOp;
955
956                 } finally {
957                         if (needLock)
958                                 unlockComponent(resultOp, containerComponent);
959                 }
960         }
961
962         public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(String componentId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
963
964                 log.debug("Try to create entry on graph");
965                 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
966
967                 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = componentInstanceOperation.associateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, inTransaction);
968
969                 if (result.isLeft()) {
970                         log.debug("Enty on graph is created.");
971                         RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
972                         resultOp = Either.left(requirementCapabilityRelDef);
973                         return resultOp;
974
975                 } else {
976                         log.debug("Failed to associate node {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
977                         String fromNameOrId = "";
978                         String toNameOrId = "";
979                         Either<ComponentInstance, StorageOperationStatus> fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode());
980                         Either<ComponentInstance, StorageOperationStatus> toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode());
981
982                         toNameOrId = requirementDef.getFromNode();
983                         fromNameOrId = requirementDef.getFromNode();
984                         if (fromResult.isLeft()) {
985                                 fromNameOrId = fromResult.left().value().getName();
986                         }
987                         if (toResult.isLeft()) {
988                                 toNameOrId = toResult.left().value().getName();
989                         }
990
991                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
992
993                         return resultOp;
994                 }
995
996         }
997
998         public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
999                 Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
1000                 if (resp.isRight()) {
1001                         return Either.right(resp.right().value());
1002                 }
1003
1004                 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1005                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, false, true);
1006                 if (validateComponentExists.isRight()) {
1007                         return Either.right(validateComponentExists.right().value());
1008                 }
1009                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1010
1011                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1012                 if (validateCanWorkOnComponent.isRight()) {
1013                         return Either.right(validateCanWorkOnComponent.right().value());
1014                 }
1015                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1016
1017                 if (lockComponent.isRight()) {
1018                         return Either.right(lockComponent.right().value());
1019                 }
1020                 try {
1021                         log.debug("Try to create entry on graph");
1022                         Either<RequirementCapabilityRelDef, StorageOperationStatus> result = componentInstanceOperation.dissociateResourceInstances(componentId, componentTypeEnum.getNodeType(), requirementDef, true);
1023                         if (result.isLeft()) {
1024                                 log.debug("Enty on graph is created.");
1025                                 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1026                                 resultOp = Either.left(requirementCapabilityRelDef);
1027                                 return resultOp;
1028
1029                         } else {
1030
1031                                 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1032                                 String fromNameOrId = "";
1033                                 String toNameOrId = "";
1034                                 Either<ComponentInstance, StorageOperationStatus> fromResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getFromNode());
1035                                 Either<ComponentInstance, StorageOperationStatus> toResult = componentInstanceOperation.getResourceInstanceById(requirementDef.getToNode());
1036
1037                                 toNameOrId = requirementDef.getFromNode();
1038                                 fromNameOrId = requirementDef.getFromNode();
1039                                 if (fromResult.isLeft()) {
1040                                         fromNameOrId = fromResult.left().value().getName();
1041                                 }
1042                                 if (toResult.isLeft()) {
1043                                         toNameOrId = toResult.left().value().getName();
1044                                 }
1045
1046                                 resultOp = Either
1047                                                 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRequirement()));
1048                                 return resultOp;
1049                         }
1050                 } finally {
1051                         unlockComponent(resultOp, containerComponent);
1052                 }
1053         }
1054
1055         private Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) {
1056                 Either<ComponentInstanceAttribute, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1057                 Either<ComponentInstanceAttribute, ResponseFormat> result;
1058                 if (eitherAttribute.isLeft()) {
1059                         log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1060                         ComponentInstanceAttribute instanceAttribute = eitherAttribute.left().value();
1061
1062                         result = Either.left(instanceAttribute);
1063
1064                 } else {
1065                         log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1066
1067                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1068
1069                         result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1070
1071                 }
1072                 return result;
1073         }
1074
1075         private Either<ComponentInstanceInput, ResponseFormat> updateInputValue(ComponentInstanceInput input, String resourceInstanceId) {
1076                 Either<ComponentInstanceInput, StorageOperationStatus> eitherInput = componentInstanceOperation.updateInputValueInResourceInstance(input, resourceInstanceId, true);
1077                 Either<ComponentInstanceInput, ResponseFormat> result;
1078                 if (eitherInput.isLeft()) {
1079                         log.debug("Input value {} was updated on graph.", input.getValueUniqueUid());
1080                         ComponentInstanceInput instanceInput = eitherInput.left().value();
1081
1082                         result = Either.left(instanceInput);
1083
1084                 } else {
1085                         log.debug("Failed to update input value {} in resource instance {}", input, resourceInstanceId);
1086
1087                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherInput.right().value());
1088
1089                         result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1090
1091                 }
1092                 return result;
1093         }
1094
1095         private Either<ComponentInstanceAttribute, ResponseFormat> createAttributeValue(ComponentInstanceAttribute attribute, String resourceInstanceId) {
1096
1097                 Either<ComponentInstanceAttribute, ResponseFormat> result;
1098
1099                 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1100                 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1101                 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1102
1103                 if (!errorWrapper.isEmpty()) {
1104                         result = Either.right(errorWrapper.getInnerElement());
1105                 } else {
1106                         Either<ComponentInstanceAttribute, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1107                         if (eitherAttribute.isLeft()) {
1108                                 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1109                                 ComponentInstanceAttribute instanceAttribute = eitherAttribute.left().value();
1110                                 result = Either.left(instanceAttribute);
1111
1112                         } else {
1113                                 log.debug("Failed to add attribute value {}  to resource instance {}", attribute, resourceInstanceId);
1114
1115                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1116                                 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1117
1118                         }
1119                 }
1120                 return result;
1121         }
1122
1123         /**
1124          * Create Or Updates Attribute Instance
1125          * 
1126          * @param componentTypeEnum
1127          * @param componentId
1128          * @param resourceInstanceId
1129          * @param attribute
1130          * @param userId
1131          * @return
1132          */
1133         public Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceAttribute attribute, String userId) {
1134                 Either<ComponentInstanceAttribute, ResponseFormat> result = null;
1135                 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1136
1137                 validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
1138                 if (errorWrapper.isEmpty()) {
1139                         validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1140                 }
1141                 if (errorWrapper.isEmpty()) {
1142                         validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1143                 }
1144                 if (errorWrapper.isEmpty()) {
1145                         validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1146                 }
1147
1148                 try {
1149                         if (errorWrapper.isEmpty()) {
1150                                 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1151                                 if (isCreate) {
1152                                         result = createAttributeValue(attribute, resourceInstanceId);
1153                                 } else {
1154                                         result = updateAttributeValue(attribute, resourceInstanceId);
1155                                 }
1156                         } else {
1157                                 result = Either.right(errorWrapper.getInnerElement());
1158                         }
1159                         return result;
1160                 }
1161
1162                 finally {
1163                         if (result == null || result.isRight()) {
1164                                 titanGenericDao.rollback();
1165                         } else {
1166                                 titanGenericDao.commit();
1167                         }
1168                         // unlock resource
1169                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1170                 }
1171         }
1172
1173         public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
1174
1175                 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1176
1177                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1178                 if (resp.isRight()) {
1179                         return Either.right(resp.right().value());
1180                 }
1181
1182                 if (componentTypeEnum == null) {
1183                         BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1184                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1185                         return resultOp;
1186                 }
1187
1188                 IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
1189
1190                 if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
1191                         log.info("Restricted operation for user {} on service {}", userId, componentId);
1192                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1193                         return resultOp;
1194                 }
1195                 // lock resource
1196                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1197                 if (lockStatus != StorageOperationStatus.OK) {
1198                         log.debug("Failed to lock service {}", componentId);
1199                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1200                         return resultOp;
1201                 }
1202                 try {
1203                         String propertyValueUid = property.getValueUniqueUid();
1204                         if (propertyValueUid == null) {
1205
1206                                 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
1207
1208                                 if (counterRes.isRight()) {
1209                                         log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
1210                                         StorageOperationStatus status = counterRes.right().value();
1211                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1212                                         resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1213                                 }
1214                                 Integer index = counterRes.left().value();
1215                                 Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.addPropertyValueToResourceInstance(property, resourceInstanceId, index, true);
1216
1217                                 if (result.isLeft()) {
1218                                         log.debug("Property value was added to resource instance {}", resourceInstanceId);
1219                                         ComponentInstanceProperty instanceProperty = result.left().value();
1220
1221                                         resultOp = Either.left(instanceProperty);
1222                                         return resultOp;
1223
1224                                 } else {
1225                                         log.debug("Failed to add property value {} to resource instance {}", property, resourceInstanceId);
1226                                         // TODO: esofer add error
1227
1228                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1229
1230                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1231
1232                                         return resultOp;
1233                                 }
1234
1235                         } else {
1236                                 Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, resourceInstanceId, true);
1237
1238                                 if (result.isLeft()) {
1239                                         log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1240                                         ComponentInstanceProperty instanceProperty = result.left().value();
1241
1242                                         resultOp = Either.left(instanceProperty);
1243                                         return resultOp;
1244
1245                                 } else {
1246                                         log.debug("Failed to update property value {} in resource instance {}", property, resourceInstanceId);
1247
1248                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1249
1250                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1251
1252                                         return resultOp;
1253                                 }
1254                         }
1255
1256                 } finally {
1257                         if (resultOp == null || resultOp.isRight()) {
1258                                 titanGenericDao.rollback();
1259                         } else {
1260                                 titanGenericDao.commit();
1261                         }
1262                         // unlock resource
1263                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1264                 }
1265
1266         }
1267
1268         public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1269
1270                 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1271
1272                 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
1273                 if (resp.isRight()) {
1274                         return Either.right(resp.right().value());
1275                 }
1276
1277                 if (componentTypeEnum == null) {
1278                         BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1279                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1280                         return resultOp;
1281                 }
1282
1283                 IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
1284
1285                 if (!ComponentValidationUtils.canWorkOnComponent(componentId, componentOperation, userId)) {
1286                         log.info("Restricted operation for user {} on service {}", userId, componentId);
1287                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1288                         return resultOp;
1289                 }
1290                 // lock resource
1291                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1292                 if (lockStatus != StorageOperationStatus.OK) {
1293                         log.debug("Failed to lock service {}", componentId);
1294                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1295                         return resultOp;
1296                 }
1297                 try {
1298                         String propertyValueUid = inputProperty.getValueUniqueUid();
1299                         if (propertyValueUid == null) {
1300
1301                                 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1302
1303                                 if (counterRes.isRight()) {
1304                                         log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1305                                         StorageOperationStatus status = counterRes.right().value();
1306                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1307                                         resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1308                                 }
1309                                 Integer index = counterRes.left().value();
1310                                 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1311
1312                                 if (result.isLeft()) {
1313                                         log.debug("Property value was added to resource instance {}", resourceInstanceId);
1314                                         ComponentInstanceInput instanceProperty = result.left().value();
1315
1316                                         resultOp = Either.left(instanceProperty);
1317                                         return resultOp;
1318
1319                                 } else {
1320                                         log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1321                                         // TODO: esofer add error
1322
1323                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1324
1325                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1326
1327                                         return resultOp;
1328                                 }
1329
1330                         } else {
1331                                 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1332
1333                                 if (result.isLeft()) {
1334                                         log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1335                                         ComponentInstanceInput instanceProperty = result.left().value();
1336
1337                                         resultOp = Either.left(instanceProperty);
1338                                         return resultOp;
1339
1340                                 } else {
1341                                         log.debug("Failed to update property value {} in reosurce instance {}", inputProperty, resourceInstanceId);
1342
1343                                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1344
1345                                         resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1346
1347                                         return resultOp;
1348                                 }
1349                         }
1350
1351                 } finally {
1352                         if (resultOp == null || resultOp.isRight()) {
1353                                 titanGenericDao.rollback();
1354                         } else {
1355                                 titanGenericDao.commit();
1356                         }
1357                         // unlock resource
1358                         graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1359                 }
1360
1361         }
1362
1363         public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1364
1365                 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
1366                 if (resp.isRight()) {
1367                         return Either.right(resp.right().value());
1368                 }
1369
1370                 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1371
1372                 if (componentTypeEnum == null) {
1373                         BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1374                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1375                         return resultOp;
1376                 }
1377
1378                 IComponentOperation componentOperation = getIComponentOperation(componentTypeEnum);
1379
1380                 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, componentOperation, userId)) {
1381                         log.info("Restricted operation for user {} on service {}", userId, serviceId);
1382                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1383                         return resultOp;
1384                 }
1385                 // lock resource
1386                 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1387                 if (lockStatus != StorageOperationStatus.OK) {
1388                         log.debug("Failed to lock service {}", serviceId);
1389                         resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1390                         return resultOp;
1391                 }
1392                 try {
1393                         Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1394
1395                         if (result.isLeft()) {
1396                                 log.debug("Property value {} was removed from graph.", propertyValueId);
1397                                 ComponentInstanceProperty instanceProperty = result.left().value();
1398
1399                                 resultOp = Either.left(instanceProperty);
1400                                 return resultOp;
1401
1402                         } else {
1403                                 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1404
1405                                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1406
1407                                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1408
1409                                 return resultOp;
1410                         }
1411
1412                 } finally {
1413                         if (resultOp == null || resultOp.isRight()) {
1414                                 titanGenericDao.rollback();
1415                         } else {
1416                                 titanGenericDao.commit();
1417                         }
1418                         // unlock resource
1419                         graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1420                 }
1421
1422         }
1423
1424         private Either<Boolean, ResponseFormat> validateComponentInstanceName(String resourceInstanceName, ComponentInstance resourceInstance, boolean isCreate) {
1425                 ComponentTypeEnum containerComponentType = getComponentTypeOfComponentInstance();
1426                 if (!isCreate) {
1427                         if (resourceInstanceName == null)
1428                                 return Either.left(true);
1429                 }
1430
1431                 if (!ValidationUtils.validateStringNotEmpty(resourceInstanceName)) {
1432                         ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, containerComponentType.getValue());
1433
1434                         return Either.right(errorResponse);
1435                 }
1436                 resourceInstance.setNormalizedName(ValidationUtils.normaliseComponentInstanceName(resourceInstanceName));
1437                 if (!isCreate) {
1438                         if (!ValidationUtils.validateResourceInstanceNameLength(resourceInstanceName)) {
1439                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, containerComponentType.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
1440
1441                                 return Either.right(errorResponse);
1442                         }
1443                         if (!ValidationUtils.validateResourceInstanceName(resourceInstanceName)) {
1444                                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, containerComponentType.getValue());
1445
1446                                 return Either.right(errorResponse);
1447                         }
1448                 }
1449
1450                 return Either.left(true);
1451
1452         }
1453
1454         private Either<Boolean, ResponseFormat> validateComponentInstanceParentState(ComponentTypeEnum containerComponentType, ComponentInstance resourceInstance) {
1455                 String componentId = resourceInstance.getComponentUid();
1456                 Either<? extends Component, StorageOperationStatus> eitherResourceResponse = Either.right(StorageOperationStatus.GENERAL_ERROR);
1457
1458                 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1459                 ComponentOperation componentOperation = getComponentOperation(componentType);
1460                 if (componentOperation != null)
1461                         eitherResourceResponse = componentOperation.getComponent(componentId, true);
1462
1463                 Component component = null;
1464                 ResponseFormat errorResponse = null;
1465                 if (eitherResourceResponse.isRight()) {
1466                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
1467                         errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1468                         return Either.right(errorResponse);
1469                 }
1470                 component = eitherResourceResponse.left().value();
1471                 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1472                 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1473                         ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1474                         errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1475                         return Either.right(errorResponse);
1476                 }
1477                 return Either.left(true);
1478         }
1479
1480         public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
1481
1482                 Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
1483                 if (resp.isRight()) {
1484                         return Either.right(resp.right().value());
1485                 }
1486
1487                 Either<ComponentInstance, ResponseFormat> resultOp = null;
1488
1489                 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1490                 if (validateComponentType.isRight()) {
1491                         return Either.right(validateComponentType.right().value());
1492                 }
1493
1494                 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1495                 final ComponentOperation containerOperation = getComponentOperation(containerComponentType);
1496
1497                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, false, true);
1498                 if (validateComponentExists.isRight()) {
1499                         return Either.right(validateComponentExists.right().value());
1500                 }
1501                 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1502
1503                 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1504                 if (validateCanWorkOnComponent.isRight()) {
1505                         return Either.right(validateCanWorkOnComponent.right().value());
1506                 }
1507
1508                 Either<Boolean, StorageOperationStatus> validateParentStatus = componentInstanceOperation.validateParent(containerComponentId, componentInstanceId, false);
1509                 if (validateParentStatus.isRight()) {
1510                         log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId);
1511                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId));
1512                         return resultOp;
1513                 }
1514                 Boolean isPrentValid = validateParentStatus.left().value();
1515                 if (!isPrentValid) {
1516                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
1517                         return resultOp;
1518
1519                 }
1520
1521                 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = componentInstanceOperation.getResourceInstanceById(componentInstanceId);
1522                 if (resourceInstanceStatus.isRight()) {
1523                         log.debug("Failed to get resource instance {} on service {}", componentInstanceId, containerComponentId);
1524                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, componentInstanceId));
1525                         return resultOp;
1526                 }
1527                 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
1528
1529                 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
1530                 if (lockComponent.isRight()) {
1531                         return Either.right(lockComponent.right().value());
1532                 }
1533
1534                 try {
1535                         if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
1536                                 resultOp = Either.left(currentResourceInstance);
1537                                 return resultOp;
1538
1539                         }
1540                         String resourceId = newComponentInstance.getComponentUid();
1541                         if (!getCompInstOriginComponentOperation().isComponentExist(resourceId)) {
1542                                 log.debug("resource {} not found.", resourceId);
1543                                 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
1544                                 return resultOp;
1545                         }
1546
1547                         // esofer - before deleting component instance, we should keep the
1548                         // groups which holds this instance
1549                         List<String> groupsToRevert = new ArrayList<>();
1550                         Either<List<String>, StorageOperationStatus> associatedGroups = groupOperation.getAssociatedGroupsToComponentInstance(componentInstanceId, true);
1551                         if (associatedGroups.isRight()) {
1552                                 StorageOperationStatus status = associatedGroups.right().value();
1553                                 if (status != StorageOperationStatus.OK) {
1554                                         BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to getch groups of current component instance", ErrorSeverity.ERROR);
1555                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1556                                         return resultOp;
1557                                 }
1558                         } else {
1559                                 List<String> groups = associatedGroups.left().value();
1560                                 groupsToRevert.addAll(groups);
1561                         }
1562                         // rbetzer - before deleting component instance, retrieve env artifacts to keep track of artifactVersion
1563
1564                         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> retrieveEnvArtifacts = componentInstanceOperation.fetchCIEnvArtifacts(componentInstanceId);
1565                         if (retrieveEnvArtifacts.isLeft())
1566                                 newComponentInstance.setDeploymentArtifacts(retrieveEnvArtifacts.left().value());
1567                         else if (retrieveEnvArtifacts.right().value() != StorageOperationStatus.OK) {
1568                                 log.debug("falied to fetch instance deployment artifacts {}", componentInstanceId );
1569                         }
1570
1571                         resultOp = deleteComponentInstance(containerComponentId, componentInstanceId, containerComponentType);
1572                         if (resultOp.isRight()) {
1573
1574                                 log.debug("failed to delete resource instance {}", resourceId);
1575
1576                                 return resultOp;
1577
1578                         }
1579
1580                         Either<Component, ResponseFormat> eitherResourceName = getOriginComponentNameFromComponentInstance(newComponentInstance, true);
1581
1582                         if (eitherResourceName.isRight()) {
1583                                 resultOp = Either.right(eitherResourceName.right().value());
1584                                 return resultOp;
1585                         }
1586
1587                         Component origComponent = eitherResourceName.left().value();
1588
1589                         ComponentInstance resResourceInfo = resultOp.left().value();
1590                         newComponentInstance.setName(resResourceInfo.getName());
1591                         newComponentInstance.setPosX(resResourceInfo.getPosX());
1592                         newComponentInstance.setPosY(resResourceInfo.getPosY());
1593                         newComponentInstance.setDescription(resResourceInfo.getDescription());
1594
1595                         resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, userId, containerOperation, true);
1596
1597                         if (resultOp.isRight()) {
1598
1599                                 log.debug("failed to create resource instance {}", resourceId);
1600
1601                                 return resultOp;
1602
1603                         }
1604
1605                         newComponentInstance = resultOp.left().value();
1606                         newComponentInstance.setName(resResourceInfo.getName());
1607                         resultOp = updateComponentInstance(containerComponentId, containerComponentType, origComponent, newComponentInstance.getUniqueId(), newComponentInstance, true);
1608
1609                         ComponentInstance updatedComponentInstance = resultOp.left().value();
1610                         if (resultOp.isRight()) {
1611                                 log.debug("failed to create resource instance {}", resourceId);
1612                                 return resultOp;
1613                         }
1614
1615                         if (false == groupsToRevert.isEmpty()) {
1616                                 StorageOperationStatus associatedGroupsToComponentInstance = groupOperation.associateGroupsToComponentInstance(groupsToRevert, updatedComponentInstance.getUniqueId(), updatedComponentInstance.getName(), true);
1617                                 if (associatedGroupsToComponentInstance != StorageOperationStatus.OK) {
1618                                         BeEcompErrorManager.getInstance().logInternalFlowError("ChangeComponentInstanceVersion", "Failed to associate groups to new component instance", ErrorSeverity.ERROR);
1619                                         resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1620                                         return resultOp;
1621                                 }
1622                         }
1623
1624                         Either<ComponentInstance, StorageOperationStatus> fullResourceInstance = componentInstanceOperation.getFullComponentInstance(resultOp.left().value(), getNodeTypeOfComponentInstanceOrigin());
1625                         if (fullResourceInstance.isRight()) {
1626                                 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fullResourceInstance.right().value()), resourceId));
1627                                 return resultOp;
1628                         }
1629                         resultOp = Either.left(fullResourceInstance.left().value());
1630                         return resultOp;
1631
1632                 } finally {
1633                         unlockComponent(resultOp, containerComponent);
1634                 }
1635         }
1636
1637         protected abstract Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent);
1638
1639         protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
1640
1641         protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
1642
1643         protected abstract ComponentOperation getContainerComponentOperation();
1644
1645         protected abstract ComponentOperation getCompInstOriginComponentOperation();
1646
1647         protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
1648                 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
1649
1650                 if (counterRes.isRight()) {
1651                         log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId);
1652                         StorageOperationStatus status = counterRes.right().value();
1653                         ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1654                         errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
1655                 } else {
1656                         instaceCounterWrapper.setInnerElement(counterRes.left().value());
1657                 }
1658
1659         }
1660
1661 }