2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.collect.Sets;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
30 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
31 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
32 import org.openecomp.sdc.be.components.validation.ComponentValidations;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
37 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
38 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
39 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
41 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
48 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
49 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
50 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
51 import org.openecomp.sdc.be.model.Component;
52 import org.openecomp.sdc.be.model.ComponentParametersView;
53 import org.openecomp.sdc.be.model.CapabilityDefinition;
54 import org.openecomp.sdc.be.model.RequirementDefinition;
55 import org.openecomp.sdc.be.model.Resource;
56 import org.openecomp.sdc.be.model.Service;
57 import org.openecomp.sdc.be.model.User;
58 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
59 import org.openecomp.sdc.be.model.LifecycleStateEnum;
60 import org.openecomp.sdc.be.model.ArtifactDefinition;
61 import org.openecomp.sdc.be.model.DataTypeDefinition;
62 import org.openecomp.sdc.be.model.PropertyDefinition;
63 import org.openecomp.sdc.be.model.GroupDefinition;
64 import org.openecomp.sdc.be.model.InputDefinition;
65 import org.openecomp.sdc.be.model.RelationshipInfo;
66 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
67 import org.openecomp.sdc.be.model.ComponentInstance;
68 import org.openecomp.sdc.be.model.ComponentInstanceInput;
69 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
70 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
71 import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
72 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
73 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
74 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
75 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
76 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
77 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
78 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
79 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
80 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
81 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
82 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
83 import org.openecomp.sdc.common.api.Constants;
84 import org.openecomp.sdc.common.datastructure.Wrapper;
85 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
86 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
87 import org.openecomp.sdc.common.log.wrappers.Logger;
88 import org.openecomp.sdc.common.util.ValidationUtils;
89 import org.openecomp.sdc.exception.ResponseFormat;
90 import org.springframework.beans.factory.annotation.Autowired;
92 import java.util.ArrayList;
93 import java.util.Collection;
94 import java.util.Collections;
95 import java.util.HashMap;
96 import java.util.Iterator;
97 import java.util.List;
99 import java.util.Map.Entry;
100 import java.util.Objects;
101 import java.util.Optional;
102 import java.util.Set;
103 import java.util.UUID;
104 import java.util.function.BiConsumer;
105 import java.util.stream.Collectors;
107 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
109 @org.springframework.stereotype.Component
110 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
112 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
113 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
114 public static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
115 public static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
116 public static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
117 public static final String INVALID_COMPONENT_TYPE = "invalid component type";
118 public static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
119 public static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
120 public static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
121 public static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
122 public static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
125 private IComponentInstanceOperation componentInstanceOperation;
128 private ArtifactsBusinessLogic artifactBusinessLogic;
131 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
134 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
137 private ForwardingPathOperation forwardingPathOperation;
139 public ComponentInstanceBusinessLogic() {
142 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
143 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
144 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
147 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
148 List<ComponentInstanceProperty> resList = new ArrayList<>();
149 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
150 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
151 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
153 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
155 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
157 ciName = ciOp.get().getName();
158 if (ciPropList != null && !ciPropList.isEmpty()) {
159 for(ComponentInstanceProperty prop: ciPropList){
160 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
161 if(inputsValues != null && !inputsValues.isEmpty()){
162 for(GetInputValueDataDefinition inputData: inputsValues){
163 if(isGetInputValueForInput(inputData, inputId)){
164 prop.setComponentInstanceId(s);
165 prop.setComponentInstanceName(ciName);
180 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
181 List<ComponentInstanceInput> resList = new ArrayList<>();
182 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
183 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
184 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
186 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
188 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
190 ciName = ciOp.get().getName();
191 if (ciPropList != null && !ciPropList.isEmpty()) {
192 for(ComponentInstanceInput prop: ciPropList){
193 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
194 if(inputsValues != null && !inputsValues.isEmpty()){
195 for(GetInputValueDataDefinition inputData: inputsValues){
196 if(isGetInputValueForInput(inputData, inputId)){
197 prop.setComponentInstanceId(s);
198 prop.setComponentInstanceName(ciName);
213 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
214 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
216 Component origComponent = null;
217 Either<ComponentInstance, ResponseFormat> resultOp = null;
219 org.openecomp.sdc.be.model.Component containerComponent = null;
220 ComponentTypeEnum containerComponentType;
223 user = validateUserExists(userId, "create Component Instance", inTransaction);
225 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
226 if (validateValidJson.isRight()) {
227 return Either.right(validateValidJson.right().value());
230 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
231 if (validateComponentType.isRight()) {
232 return Either.right(validateComponentType.right().value());
234 containerComponentType = validateComponentType.left().value();
237 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
238 if (validateComponentExists.isRight()) {
239 return Either.right(validateComponentExists.right().value());
241 containerComponent = validateComponentExists.left().value();
244 if (ModelConverter.isAtomicComponent(containerComponent)) {
245 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
246 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
249 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
250 if (validateCanWorkOnComponent.isRight()) {
251 return Either.right(validateCanWorkOnComponent.right().value());
254 if (resourceInstance != null && containerComponentType != null) {
255 OriginTypeEnum originType = resourceInstance.getOriginType();
256 if (originType == OriginTypeEnum.ServiceProxy) {
257 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
258 if (serviceProxyOrigin.isRight()) {
259 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
260 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
262 origComponent = serviceProxyOrigin.left().value();
264 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
265 if (fillProxyRes != StorageOperationStatus.OK) {
266 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
267 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
272 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
274 if (getOriginComponentRes.isRight()) {
275 return Either.right(getOriginComponentRes.right().value());
277 origComponent = getOriginComponentRes.left().value();
282 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
283 if (lockComponent.isRight()) {
284 return Either.right(lockComponent.right().value());
287 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
288 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
293 unlockComponent(resultOp, containerComponent);
297 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
298 resourceInstance.setIsProxy(true);
299 ComponentParametersView filter = new ComponentParametersView(true);
300 filter.setIgnoreCapabilities(false);
301 filter.setIgnoreCapabiltyProperties(false);
302 filter.setIgnoreComponentInstances(false);
303 filter.setIgnoreRequirements(false);
304 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
305 if (serviceRes.isRight()) {
306 return serviceRes.right().value();
308 Component service = serviceRes.left().value();
309 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
310 resourceInstance.setCapabilities(capabilities);
311 Map<String, List<RequirementDefinition>> req = service.getRequirements();
312 resourceInstance.setRequirements(req);
314 String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
315 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
316 int lastIndexOf = toscaResourceName.lastIndexOf('.');
317 if (lastIndexOf != -1) {
318 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
319 resourceInstance.setToscaComponentName(proxyToscaName);
321 resourceInstance.setName(name);
322 resourceInstance.setIsProxy(true);
323 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
324 resourceInstance.setSourceModelName(service.getName());
325 resourceInstance.setSourceModelUuid(service.getUUID());
326 resourceInstance.setSourceModelUid(service.getUniqueId());
327 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
328 resourceInstance.setDescription("A Proxy for Service " + service.getName());
329 resourceInstance.setComponentVersion(service.getVersion());
331 return StorageOperationStatus.OK;
334 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
336 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
337 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
338 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
340 User user = validateUserExists(userId, "create And Associate RI To RI", false);
342 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
343 if (validateComponentType.isRight()) {
344 return Either.right(validateComponentType.right().value());
347 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
349 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
350 if (validateComponentExists.isRight()) {
351 return Either.right(validateComponentExists.right().value());
353 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
355 if (ModelConverter.isAtomicComponent(containerComponent)) {
356 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
357 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
360 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
361 if (validateCanWorkOnComponent.isRight()) {
362 return Either.right(validateCanWorkOnComponent.right().value());
365 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
366 if (lockComponent.isRight()) {
367 return Either.right(lockComponent.right().value());
371 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
372 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
374 if (eitherResourceName.isRight()) {
375 resultOp = Either.right(eitherResourceName.right().value());
378 Component origComponent = eitherResourceName.left().value();
380 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
381 if (result.isRight()) {
382 log.debug("Failed to create resource instance {}", containerComponentId);
383 resultOp = Either.right(result.right().value());
388 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
389 ComponentInstance resResourceInfo = result.left().value();
390 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
391 associationInfo.setFromNode(resResourceInfo.getUniqueId());
393 associationInfo.setToNode(resResourceInfo.getUniqueId());
396 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
397 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
398 if (resultReqCapDef.isLeft()) {
399 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
400 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
401 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
402 resultOp = Either.left(resInfo);
406 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
407 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
412 unlockComponent(resultOp, containerComponent);
416 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
417 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
420 private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
421 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
424 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
425 Either<Component, ResponseFormat> eitherResponse;
426 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
427 if (eitherComponent.isRight()) {
428 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
429 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
431 eitherResponse = Either.left(eitherComponent.left().value());
433 return eitherResponse;
436 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
437 Either<ComponentInstance, ResponseFormat> resultOp;
439 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
441 if (result.isRight()) {
442 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
443 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
447 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
448 Component updatedComponent = result.left().value().getLeft();
449 Map<String, String> existingEnvVersions = new HashMap<>();
450 // TODO existingEnvVersions ??
451 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
452 if (addComponentInstanceArtifacts.isRight()) {
453 log.debug("Failed to create component instance {}", componentInstance.getName());
454 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
458 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
459 if (!updatedInstanceOptional.isPresent()) {
460 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
461 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
464 resultOp = Either.left(updatedInstanceOptional.get());
469 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
470 * @param containerComponent
471 * @param componentInstance
472 * @param originComponent
474 * @param existingEnvVersions
477 protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
479 log.debug("add artifacts to resource instance");
480 List<GroupDefinition> filteredGroups = null;
481 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
482 if (!ActionStatus.OK.equals(status)) {
483 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
484 return Either.right(resultOp);
486 StorageOperationStatus artStatus;
487 // generate heat_env if necessary
488 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
489 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
491 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
492 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
494 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
495 String type = artifact.getArtifactType();
496 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
497 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
499 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
502 if (artifact.checkEsIdExist()) {
503 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
504 componentInstance.getName(), user, containerComponent, existingEnvVersions);
505 if (createHeatEnvPlaceHolder.isRight()) {
506 return Either.right(createHeatEnvPlaceHolder.right().value());
508 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
510 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
512 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
513 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
515 if (CollectionUtils.isNotEmpty(filteredGroups)) {
516 for (GroupDefinition groupInstance : filteredGroups) {
517 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
518 if (op.isPresent()) {
519 List<ArtifactDefinition> artifactsUid;
520 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
521 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
523 artifactsUid = new ArrayList<>();
525 artifactsUid.add(artifactDefinition);
526 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
533 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
534 if (artStatus != StorageOperationStatus.OK) {
535 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
536 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
539 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
540 if (result != StorageOperationStatus.OK) {
541 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
542 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
544 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
547 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
548 if (artStatus != StorageOperationStatus.OK) {
549 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
550 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
553 componentInstance.setArtifacts(originComponent.getArtifacts());
554 return Either.left(ActionStatus.OK);
557 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
558 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
560 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
561 if (getResourceDeploymentArtifacts.isRight()) {
562 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
563 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
564 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
565 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
568 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
571 if (!deploymentArtifacts.isEmpty()) {
572 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
573 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
574 if (!artifact.getValue().checkEsIdExist()) {
575 tempDeploymentArtifacts.remove(artifact.getKey());
579 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
582 return ActionStatus.OK;
585 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
586 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
589 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
590 boolean needLock, boolean createNewTransaction) {
592 validateUserExists(userId, "update Component Instance", inTransaction);
594 Either<ComponentInstance, ResponseFormat> resultOp = null;
596 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
597 if (validateComponentType.isRight()) {
598 return Either.right(validateComponentType.right().value());
601 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
603 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
604 if (validateComponentExists.isRight()) {
605 return Either.right(validateComponentExists.right().value());
607 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
609 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
610 if (validateCanWorkOnComponent.isRight()) {
611 return Either.right(validateCanWorkOnComponent.right().value());
613 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
614 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
615 if (validateParentStatus.isRight()) {
616 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
617 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
620 if (!validateParentStatus.left().value()) {
621 resultOp = Either.right(
622 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
627 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
628 if (lockComponent.isRight()) {
629 return Either.right(lockComponent.right().value());
634 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
636 if (eitherResourceName.isRight()) {
637 resultOp = Either.right(eitherResourceName.right().value());
640 Component origComponent = eitherResourceName.left().value();
642 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
647 unlockComponent(resultOp, containerComponent);
651 // New Multiple Instance Update API
652 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
654 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
655 org.openecomp.sdc.be.model.Component containerComponent = null;
657 validateUserExists(userId, "update Component Instance", true);
659 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
660 if (validateComponentType.isRight()) {
661 return Either.right(validateComponentType.right().value());
664 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
666 ComponentParametersView componentFilter = new ComponentParametersView();
667 componentFilter.disableAll();
668 componentFilter.setIgnoreUsers(false);
669 componentFilter.setIgnoreComponentInstances(false);
670 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
671 if (validateComponentExists.isRight()) {
672 return Either.right(validateComponentExists.right().value());
675 containerComponent = validateComponentExists.left().value();
677 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
678 if (validateCanWorkOnComponent.isRight()) {
679 return Either.right(validateCanWorkOnComponent.right().value());
682 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
684 for (ComponentInstance componentInstance : componentInstanceList) {
685 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
686 if (!validateParent) {
687 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
688 containerComponentId));
695 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
696 if (lockComponent.isRight()) {
697 return Either.right(lockComponent.right().value());
701 List<ComponentInstance> updatedList = new ArrayList<>();
702 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
703 List<ComponentInstance> listForUpdate = new ArrayList<>();
704 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
705 containerComponent.setComponentInstances(componentInstanceList);
707 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
708 while (iterator.hasNext()) {
709 ComponentInstance origInst = iterator.next();
710 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
711 if (op.isPresent()) {
712 ComponentInstance updatedCi = op.get();
713 updatedCi = buildComponentInstance(updatedCi, origInst);
715 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
717 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
718 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
722 listForUpdate.add(updatedCi);
724 listForUpdate.add(origInst);
726 containerComponent.setComponentInstances(listForUpdate);
728 if (resultOp == null) {
729 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
730 if (updateStatus.isRight()) {
731 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
732 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
735 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
736 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
737 if (op.isPresent()) {
738 updatedList.add(updatedInstance);
744 resultOp = Either.left(updatedList);
749 unlockComponent(resultOp, containerComponent);
754 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
755 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
758 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
759 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
760 return ComponentTypeEnum.SERVICE_INSTANCE;
762 return ComponentTypeEnum.RESOURCE_INSTANCE;
766 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
767 ComponentInstance componentInstance) {
769 Either<ComponentInstance, ResponseFormat> resultOp = null;
770 Optional<ComponentInstance> componentInstanceOptional = null;
771 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
772 ComponentInstance oldComponentInstance = null;
773 boolean isNameChanged = false;
775 if (resultOp == null) {
776 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
777 if (!componentInstanceOptional.isPresent()) {
778 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
779 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
782 if (resultOp == null) {
783 oldComponentInstance = componentInstanceOptional.get();
784 String newInstanceName = componentInstance.getName();
785 if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
786 isNameChanged = true;
787 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
789 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
790 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
793 if (resultOp == null) {
794 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
795 if (updateRes.isRight()) {
796 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
797 updateRes.right().value());
798 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
800 // region - Update instance Groups
802 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
803 if (result.isRight())
804 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
809 if (resultOp == null) {
810 String newInstanceId = updateRes.left().value().getRight();
811 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
813 if (!updatedInstanceOptional.isPresent()) {
814 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
815 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
817 resultOp = Either.left(updatedInstanceOptional.get());
821 if (resultOp == null) {
822 resultOp = Either.left(componentInstanceOptional.get());
829 * The normalized old vf name
830 * @param newNormailzedPrefix-
831 * The normalized new vf name
832 * @param qualifiedGroupInstanceName-
833 * old Group Instance Name
835 // modify group names
836 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
837 if (qualifiedGroupInstanceName == null) {
838 log.info("CANNOT change group name ");
841 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
842 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
843 return qualifiedGroupInstanceName;
846 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
847 oldComponentInstance.setName(newComponentInstance.getName());
848 oldComponentInstance.setModificationTime(System.currentTimeMillis());
849 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
850 if (oldComponentInstance.getGroupInstances() != null)
851 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
852 return oldComponentInstance;
855 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
857 validateUserExists(userId, "delete Component Instance", false);
859 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
860 if (validateComponentType.isRight()) {
861 return Either.right(validateComponentType.right().value());
864 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
865 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
866 if (validateComponentExists.isRight()) {
867 return Either.right(validateComponentExists.right().value());
869 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
870 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
871 if (validateCanWorkOnComponent.isRight()) {
872 return Either.right(validateCanWorkOnComponent.right().value());
875 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
876 if (lockComponent.isRight()) {
877 return Either.right(lockComponent.right().value());
880 Either<ComponentInstance, ResponseFormat> resultOp = null;
882 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
883 if (resultOp.isRight()){
886 Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
887 containerComponentType, resultOp);
888 if (deleteEither.isRight()){
894 unlockComponent(resultOp, containerComponent);
898 public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
899 Either<ComponentInstance, ResponseFormat> resultOp) {
900 if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
901 final ComponentInstance componentInstance = resultOp.left().value();
902 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
903 if (!pathIDsToBeDeleted.isEmpty()) {
904 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
906 if(deleteForwardingPathsEither.isRight()) {
907 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
916 private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
918 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
919 if(storageStatus.isRight()) {
920 return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
922 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
923 Sets.newHashSet(pathIdsToDelete));
925 if(result.isRight()) {
926 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
928 return Either.left(result.left().value());
931 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
932 ComponentParametersView filter = new ComponentParametersView(true);
933 filter.setIgnoreForwardingPath(false);
934 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
935 .getToscaElement(containerComponentId, filter);
936 Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
937 List<String> pathIDsToBeDeleted = new ArrayList<>();
939 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
940 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
942 return pathIDsToBeDeleted;
945 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
946 String componentInstanceId){
947 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
948 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
949 elementDataDefinition.getToNode()
950 .equalsIgnoreCase(componentInstanceId));
954 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
956 Either<ComponentInstance, ResponseFormat> resultOp = null;
957 ComponentInstance deletedInstance = null;
958 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
960 if (deleteRes.isRight()) {
961 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
962 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
963 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
965 if (resultOp == null) {
966 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
967 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
968 resultOp = Either.left(deletedInstance);
970 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
971 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
972 for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
973 Map<String, String> members = currGroup.getMembers();
974 if (members != null && members.containsKey(deletedInstance.getName())) {
975 members.remove(deletedInstance.getName());
976 groupsToUpdate.add(currGroup);
979 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
980 if (updateGroupsRes.isRight()) {
981 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
982 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
983 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
986 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
987 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
988 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
989 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
990 if (deleteInputsRes != StorageOperationStatus.OK) {
991 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
992 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
999 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1000 ComponentInstance foundInstance = null;
1001 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1002 if (instance.getUniqueId().equals(componentInstanceId)) {
1003 foundInstance = instance;
1004 containerComponent.getComponentInstances().remove(instance);
1008 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1009 return foundInstance;
1012 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1013 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1014 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1018 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1019 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1022 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1023 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1026 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1027 boolean createNewTransaction) {
1029 validateUserExists(userId, "associate Ri To RI", inTransaction);
1031 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1033 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1034 if (validateComponentExists.isRight()) {
1035 return Either.right(validateComponentExists.right().value());
1037 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1039 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1040 if (validateCanWorkOnComponent.isRight()) {
1041 return Either.right(validateCanWorkOnComponent.right().value());
1044 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1046 if (lockComponent.isRight()) {
1047 return Either.right(lockComponent.right().value());
1053 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1059 unlockComponent(resultOp, containerComponent);
1063 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1065 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1066 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1068 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1070 if (result.isLeft()) {
1071 log.debug("Enty on graph is created.");
1072 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1073 resultOp = Either.left(requirementCapabilityRelDef);
1077 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1078 String fromNameOrId = "";
1079 String toNameOrId = "";
1080 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1081 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1083 toNameOrId = requirementDef.getFromNode();
1084 fromNameOrId = requirementDef.getFromNode();
1085 if (fromResult.isLeft()) {
1086 fromNameOrId = fromResult.left().value().getName();
1088 if (toResult.isLeft()) {
1089 toNameOrId = toResult.left().value().getName();
1092 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1100 * @param componentId
1102 * @param requirementDefList
1103 * @param componentTypeEnum
1106 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1109 List<RequirementCapabilityRelDef> requirementDefList,
1110 ComponentTypeEnum componentTypeEnum) {
1112 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1113 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1114 if (validateResponse.isRight()) {
1118 Component containerComponent = validateResponse.left().value();
1119 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1120 if (lockComponent.isRight()) {
1124 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1125 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = dissociateRIFromRI(
1126 componentId, requirementDef, containerComponent);
1128 if (actionResponse.isLeft()) {
1129 delOkResult.add(actionResponse.left().value());
1133 unlockComponent(validateResponse, containerComponent);
1138 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1139 String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1140 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1141 if(validateResponse.isRight())
1143 return Either.right(validateResponse.right().value());
1145 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = null;
1146 Component containerComponent = validateResponse.left().value();
1147 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1148 if (lockComponent.isRight()) {
1149 return Either.right(lockComponent.right().value());
1152 actionResponse = dissociateRIFromRI(
1153 componentId, requirementDef,containerComponent);
1155 unlockComponent(validateResponse, containerComponent);
1157 return actionResponse;
1160 private Either<Component, ResponseFormat> validateDissociateRI(
1161 String componentId, String userId, ComponentTypeEnum componentTypeEnum) {
1162 validateUserExists(userId, "dissociate RI From RI", false);
1165 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1166 if (validateComponentExists.isRight()) {
1167 return Either.right(validateComponentExists.right().value());
1169 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1171 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1172 if (validateCanWorkOnComponent.isRight()) {
1173 return Either.right(validateCanWorkOnComponent.right().value());
1175 return Either.left(containerComponent);
1178 private Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1179 String componentId, RequirementCapabilityRelDef requirementDef, Component containerComponent) {
1181 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1182 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1183 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(
1184 componentId, requirementDef);
1185 if (result.isLeft()) {
1186 log.debug("Enty on graph is created.");
1187 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1188 resultOp = Either.left(requirementCapabilityRelDef);
1193 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1194 String fromNameOrId = "";
1195 String toNameOrId = "";
1196 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(
1197 containerComponent, requirementDef.getFromNode());
1198 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(
1199 containerComponent, requirementDef.getToNode());
1201 toNameOrId = requirementDef.getFromNode();
1202 fromNameOrId = requirementDef.getFromNode();
1203 if (fromResult.isLeft()) {
1204 fromNameOrId = fromResult.left().value().getName();
1206 if (toResult.isLeft()) {
1207 toNameOrId = toResult.left().value().getName();
1211 .right(componentsUtils.getResponseFormat(
1212 componentsUtils.convertFromStorageResponseForResourceInstance(
1213 result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1219 * Allows to get relation contained in specified component according to received Id
1220 * @param componentId
1223 * @param componentTypeEnum
1226 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1228 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1230 org.openecomp.sdc.be.model.Component containerComponent = null;
1231 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1232 RequirementCapabilityRelDef foundRelation = null;
1234 validateUserExists(userId, "get relation by Id", false);
1236 if(resultOp == null){
1237 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1238 if (validateComponentExists.isRight()) {
1239 resultOp = Either.right(validateComponentExists.right().value());
1242 if(resultOp == null){
1243 containerComponent = validateComponentExists.left().value();
1244 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1245 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1246 if(foundRelation == null){
1247 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1248 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1249 resultOp = Either.right(responseFormat);
1252 if(resultOp == null){
1253 resultOp = setRelatedCapability(foundRelation, containerComponent);
1255 if(resultOp.isLeft()){
1256 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1258 } catch (Exception e) {
1259 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1260 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1265 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1266 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1267 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1268 return relationship;
1274 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1275 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1276 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1277 String instanceId = foundRelation.getFromNode();
1278 Optional<RequirementDefinition> foundRequirement;
1279 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1280 if(!instance.isPresent()){
1281 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1282 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1283 result = Either.right(responseFormat);
1286 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1287 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1288 if(foundRequirement.isPresent()){
1289 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1290 result = Either.left(foundRelation);
1295 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1296 if(getfulfilledRequirementRes.isRight()){
1297 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1298 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1299 result = Either.right(responseFormat);
1301 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1305 result = Either.left(foundRelation);
1310 private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1311 return req.getName().equals(relationshipInfo.getRequirement()) &&
1312 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1313 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1316 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1317 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1318 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1319 String instanceId = foundRelation.getToNode();
1320 Optional<CapabilityDefinition> foundCapability;
1321 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1322 if(!instance.isPresent()){
1323 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1324 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1325 result = Either.right(responseFormat);
1328 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1329 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1330 if(foundCapability.isPresent()){
1331 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1332 result = Either.left(foundRelation);
1337 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1338 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1339 if(getfulfilledRequirementRes.isRight()){
1340 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1341 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1342 result = Either.right(responseFormat);
1344 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1348 result = Either.left(foundRelation);
1353 private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1354 return cap.getName().equals(relationshipInfo.getCapability()) &&
1355 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1356 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1359 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1360 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1361 Either<ComponentInstanceProperty, ResponseFormat> result;
1362 if (eitherAttribute.isLeft()) {
1363 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1364 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1366 result = Either.left(instanceAttribute);
1369 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1371 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1373 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1379 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1381 Either<ComponentInstanceProperty, ResponseFormat> result;
1383 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1384 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1385 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1387 if (!errorWrapper.isEmpty()) {
1388 result = Either.right(errorWrapper.getInnerElement());
1390 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1391 if (eitherAttribute.isLeft()) {
1392 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1393 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1394 result = Either.left(instanceAttribute);
1397 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1399 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1400 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1408 * Create Or Updates Attribute Instance
1410 * @param componentTypeEnum
1411 * @param componentId
1412 * @param resourceInstanceId
1417 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1418 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1419 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1421 validateUserExist(userId, "create Or Update Attribute Value");
1422 if (errorWrapper.isEmpty()) {
1423 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1425 if (errorWrapper.isEmpty()) {
1426 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1428 if (errorWrapper.isEmpty()) {
1429 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1433 if (errorWrapper.isEmpty()) {
1434 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1436 result = createAttributeValue(attribute, resourceInstanceId);
1438 result = updateAttributeValue(attribute, resourceInstanceId);
1441 result = Either.right(errorWrapper.getInnerElement());
1447 if (result == null || result.isRight()) {
1448 titanDao.rollback();
1453 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1457 private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1458 return StringUtils.isNotEmpty(property.getValue())
1459 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1460 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1463 // US833308 VLI in service - specific network_role property value logic
1464 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1465 for (ComponentInstanceProperty property: properties) {
1466 if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1467 ComponentParametersView componentParametersView = new ComponentParametersView();
1468 componentParametersView.disableAll();
1469 componentParametersView.setIgnoreComponentInstances(false);
1470 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1471 if (getServiceResult.isRight()) {
1472 return getServiceResult.right().value();
1474 Component service = getServiceResult.left().value();
1475 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1476 if (!getInstance.isPresent()) {
1477 return StorageOperationStatus.NOT_FOUND;
1479 String prefix = service.getSystemName() + ".";
1480 String value = property.getValue();
1481 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1482 property.setValue(prefix + value);
1486 return StorageOperationStatus.OK;
1489 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1491 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1493 /*-------------------------------Validations---------------------------------*/
1495 validateUserExists(userId, "create Or Update Properties Values", false);
1497 if (componentTypeEnum == null) {
1498 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1499 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1502 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1504 if (getResourceResult.isRight()) {
1505 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1506 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1509 Component containerComponent = getResourceResult.left().value();
1511 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1512 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1513 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1516 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1517 if (resourceInstanceStatus.isRight()) {
1518 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1521 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1522 // specific property value logic US833308
1523 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1524 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1525 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1529 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1530 if (lockStatus != StorageOperationStatus.OK) {
1531 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1532 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1537 for (ComponentInstanceProperty property: properties) {
1538 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1539 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1540 responseFormat -> Either.right(responseFormat));
1543 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1544 if (updateContainerRes.isRight()) {
1545 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1546 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1549 resultOp = Either.left(properties);
1553 if (resultOp == null || resultOp.isRight()) {
1554 titanDao.rollback();
1559 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1563 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1564 String capabilityType, String capabilityName) {
1565 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1566 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
1567 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1568 String capKey = sb.toString();
1570 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1571 .orElse(Collections.emptyMap());
1572 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
1573 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1574 if (cap.isPresent()) {
1575 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1576 if (capProperties != null) {
1577 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1578 StorageOperationStatus status;
1579 if (instanceProperty.isPresent()) {
1580 instanceProperty.get().setValue(newValue);
1581 List<String> path = new ArrayList<>();
1582 path.add(componentInstanceUniqueId);
1584 instanceProperty.get().setPath(path);
1585 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1586 if (status != StorageOperationStatus.OK) {
1587 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1588 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1591 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1597 return componentsUtils.getResponseFormat(ActionStatus.OK);
1600 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1601 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1602 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1603 StorageOperationStatus status;
1604 instanceProperty.get().setValue(newValue);
1605 if (instanceProperty.isPresent()) {
1606 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1608 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1610 if (status != StorageOperationStatus.OK) {
1611 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1612 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1614 List<String> path = new ArrayList<>();
1615 path.add(foundResourceInstance.getUniqueId());
1616 property.setPath(path);
1618 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1619 return componentsUtils.getResponseFormat(ActionStatus.OK);
1622 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1623 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1624 if (allDataTypesEither.isRight()) {
1625 TitanOperationStatus status = allDataTypesEither.right().value();
1626 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1627 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1629 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1630 String innerType = null;
1631 String propertyType = property.getType();
1632 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1633 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1635 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1636 SchemaDefinition def = property.getSchema();
1638 log.debug("Schema doesn't exists for property of type {}", type);
1639 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1641 PropertyDataDefinition propDef = def.getProperty();
1642 if (propDef == null) {
1643 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1644 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1646 innerType = propDef.getType();
1648 // Specific Update Logic
1649 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1650 String newValue = property.getValue();
1651 if (isValid.isRight()) {
1652 Boolean res = isValid.right().value();
1654 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1657 Object object = isValid.left().value();
1658 if (object != null) {
1659 newValue = object.toString();
1663 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1664 if (pair.getRight() != null && pair.getRight() == false) {
1665 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1666 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1669 return Either.left(newValue);
1672 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1673 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1674 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1675 StorageOperationStatus status;
1676 if (instanceProperty.isPresent()) {
1677 instanceProperty.get().setValue(input.getValue());
1678 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1680 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1682 if (status != StorageOperationStatus.OK) {
1683 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1684 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1686 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1687 return componentsUtils.getResponseFormat(ActionStatus.OK);
1690 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1692 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1694 validateUserExists(userId, "create Or Update Property Value", false);
1696 if (componentTypeEnum == null) {
1697 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1698 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1701 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1703 if (getResourceResult.isRight()) {
1704 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1705 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1708 Component containerComponent = getResourceResult.left().value();
1710 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1711 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1712 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1715 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1716 if (resourceInstanceStatus.isRight()) {
1717 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1721 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1724 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1725 if (lockStatus != StorageOperationStatus.OK) {
1726 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1727 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1731 for (ComponentInstanceInput input: inputs) {
1732 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1733 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1737 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1739 if (updateContainerRes.isRight()) {
1740 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1741 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1744 resultOp = Either.left(inputs);
1748 if (resultOp == null || resultOp.isRight()) {
1749 titanDao.rollback();
1754 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1759 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1762 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1764 validateUserExists(userId, "create Or Update Property Value", false);
1766 if (componentTypeEnum == null) {
1767 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1768 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1772 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1773 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1774 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1778 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1779 if (lockStatus != StorageOperationStatus.OK) {
1780 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1781 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1785 String propertyValueUid = property.getValueUniqueUid();
1787 if (propertyValueUid == null) {
1789 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1791 if (counterRes.isRight()) {
1792 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1793 StorageOperationStatus status = counterRes.right().value();
1794 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1795 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1797 Integer index = counterRes.left().value();
1798 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1800 if (result.isLeft()) {
1801 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1802 ComponentInstanceProperty instanceProperty = result.left().value();
1804 resultOp = Either.left(instanceProperty);
1807 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1809 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1811 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1815 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1817 if (result.isLeft()) {
1818 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1819 ComponentInstanceProperty instanceProperty = result.left().value();
1821 resultOp = Either.left(instanceProperty);
1824 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1826 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1828 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1831 if (resultOp.isLeft()) {
1832 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1833 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1834 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1836 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1843 if (resultOp == null || resultOp.isRight()) {
1844 titanDao.rollback();
1849 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1854 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1856 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1858 validateUserExists(userId, "create Or Update Input Value", false);
1860 if (componentTypeEnum == null) {
1861 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1862 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1866 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1867 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1868 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1872 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1873 if (lockStatus != StorageOperationStatus.OK) {
1874 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1875 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1879 String propertyValueUid = inputProperty.getValueUniqueUid();
1880 if (propertyValueUid == null) {
1882 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1884 if (counterRes.isRight()) {
1885 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1886 StorageOperationStatus status = counterRes.right().value();
1887 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1888 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1890 Integer index = counterRes.left().value();
1891 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1893 if (result.isLeft()) {
1894 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1895 ComponentInstanceInput instanceProperty = result.left().value();
1897 resultOp = Either.left(instanceProperty);
1901 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1903 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1905 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1911 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1913 if (result.isLeft()) {
1914 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1915 ComponentInstanceInput instanceProperty = result.left().value();
1917 resultOp = Either.left(instanceProperty);
1921 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1923 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1925 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1932 if (resultOp == null || resultOp.isRight()) {
1933 titanDao.rollback();
1938 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1943 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1945 validateUserExists(userId, "delete Property Value", false);
1947 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1949 if (componentTypeEnum == null) {
1950 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1951 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1955 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1956 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1957 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1961 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1962 if (lockStatus != StorageOperationStatus.OK) {
1963 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
1964 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1968 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1970 if (result.isLeft()) {
1971 log.debug("Property value {} was removed from graph.", propertyValueId);
1972 ComponentInstanceProperty instanceProperty = result.left().value();
1974 resultOp = Either.left(instanceProperty);
1978 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1980 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1982 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1988 if (resultOp == null || resultOp.isRight()) {
1989 titanDao.rollback();
1994 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1999 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
2001 Either<Component, ResponseFormat> eitherResponse = null;
2002 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
2003 Component component;
2004 ResponseFormat errorResponse;
2005 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2006 if (getComponentRes.isRight()) {
2007 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2008 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2009 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2010 eitherResponse = Either.right(errorResponse);
2012 if (eitherResponse == null) {
2013 component = getComponentRes.left().value();
2014 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2015 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2016 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
2017 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
2018 eitherResponse = Either.right(errorResponse);
2021 if (eitherResponse == null) {
2022 eitherResponse = Either.left(getComponentRes.left().value());
2024 return eitherResponse;
2027 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2028 String containerComponentId,
2029 String componentInstanceId,
2030 ComponentInstance newComponentInstance) {
2031 Either<Set<String>, ResponseFormat> resultOp;
2032 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2033 if (validateComponentType.isRight()) {
2034 return Either.right(validateComponentType.right().value());
2036 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2037 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2040 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
2041 validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2042 if (validateComponentExists.isRight()) {
2043 return Either.right(validateComponentExists.right().value());
2045 Component containerComponent = validateComponentExists.left().value();
2047 //Fetch current component instance
2048 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2049 getResourceInstanceById(containerComponent, componentInstanceId);
2050 if (eitherResourceInstance.isRight()) {
2051 resultOp = Either.right(componentsUtils.getResponseFormat(
2052 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2055 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2057 //Check whether new componentInstance exists
2058 String resourceId = newComponentInstance.getComponentUid();
2059 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2060 if (componentExistsRes.isRight()) {
2061 log.debug("Failed to find resource {} ", resourceId);
2062 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2063 (componentExistsRes.right().value()), resourceId));
2065 } else if (!componentExistsRes.left().value()) {
2066 log.debug("The resource {} not found ", resourceId);
2067 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2071 //Fetch component using new component instance uid
2072 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2073 if (eitherResourceName.isRight()) {
2074 resultOp = Either.right(eitherResourceName.right().value());
2077 Component updatedContainerComponent=eitherResourceName.left().value();
2078 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2079 currentResourceInstance, updatedContainerComponent);
2080 resultOp=Either.left(toDeleteForwardingPaths);
2085 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2086 Component updatedContainerComponent) {
2087 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2088 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2090 Service service = (Service) containerComponent;
2091 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2093 return forwardingPathUtils.
2094 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2097 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2098 ComponentParametersView componentParametersView = new ComponentParametersView();
2099 componentParametersView.setIgnoreCapabiltyProperties(false);
2100 componentParametersView.setIgnoreForwardingPath(false);
2101 return componentParametersView;
2104 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2106 User user = validateUserExists(userId, "change Component Instance Version", false);
2108 Either<ComponentInstance, ResponseFormat> resultOp = null;
2110 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2111 if (validateComponentType.isRight()) {
2112 return Either.right(validateComponentType.right().value());
2115 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2116 ComponentParametersView componentParametersView = new ComponentParametersView();
2117 componentParametersView.setIgnoreCapabiltyProperties(false);
2118 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2119 if (validateComponentExists.isRight()) {
2120 return Either.right(validateComponentExists.right().value());
2122 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2124 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2125 if (validateCanWorkOnComponent.isRight()) {
2126 return Either.right(validateCanWorkOnComponent.right().value());
2129 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2130 if (resourceInstanceStatus.isRight()) {
2131 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2135 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2137 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2140 public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2141 ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
2142 Either<ComponentInstance, ResponseFormat> resultOp = null;
2143 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2145 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2146 String containerComponentId = containerComponent.getUniqueId();
2147 String componentInstanceId = currentResourceInstance.getUniqueId();
2148 if (lockComponent.isRight()) {
2149 return Either.right(lockComponent.right().value());
2155 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2156 resultOp = Either.left(currentResourceInstance);
2160 String resourceId = newComponentInstance.getComponentUid();
2164 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2165 if (componentExistsRes.isRight()) {
2166 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2167 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2169 } else if (!componentExistsRes.left().value()) {
2170 log.debug("The resource {} not found ", resourceId);
2171 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2175 Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2177 if (eitherOriginComponent.isRight()) {
2178 resultOp = Either.right(eitherOriginComponent.right().value());
2181 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2182 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2183 if (resultOp.isRight()) {
2184 log.debug("failed to delete resource instance {}", resourceId);
2187 ComponentInstance resResourceInfo = resultOp.left().value();
2188 Component origComponent = null;
2189 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2190 if (originType == OriginTypeEnum.ServiceProxy) {
2191 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2192 if (serviceProxyOrigin.isRight()) {
2193 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2194 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2196 origComponent = serviceProxyOrigin.left().value();
2198 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2200 if (fillProxyRes != StorageOperationStatus.OK) {
2201 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2202 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2205 newComponentInstance.setOriginType(originType);
2209 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2211 if (eitherResourceName.isRight()) {
2212 resultOp = Either.right(eitherResourceName.right().value());
2216 origComponent = eitherResourceName.left().value();
2218 newComponentInstance.setName(resResourceInfo.getName());
2221 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2222 newComponentInstance.setPosX(resResourceInfo.getPosX());
2223 newComponentInstance.setPosY(resResourceInfo.getPosY());
2224 newComponentInstance.setDescription(resResourceInfo.getDescription());
2226 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2228 if (resultOp.isRight()) {
2229 log.debug("failed to create resource instance {}", resourceId);
2233 ComponentInstance updatedComponentInstance = resultOp.left().value();
2234 if (resultOp.isRight()) {
2235 log.debug("failed to create resource instance {}", resourceId);
2239 Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2240 if (mergeStatusEither.isRight()) {
2241 return Either.right(mergeStatusEither.right().value());
2244 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2245 if (postChangeVersionResult != ActionStatus.OK) {
2246 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2249 ComponentParametersView filter = new ComponentParametersView(true);
2250 filter.setIgnoreComponentInstances(false);
2251 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2252 if (updatedComponentRes.isRight()) {
2253 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2254 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2255 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2256 log.debug("Component with id {} was not found", containerComponentId);
2257 return Either.right(responseFormat);
2259 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2260 if (resourceInstanceStatus.isRight()) {
2261 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2264 resultOp = Either.left(resourceInstanceStatus.left().value());
2268 unlockComponent(resultOp, containerComponent);
2273 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2274 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2275 Component containerComponent = null;
2277 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2279 validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2281 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2282 if (validateComponentType.isRight()) {
2283 resultOp = Either.right(validateComponentType.right().value());
2287 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2288 if (validateContainerComponentExists.isRight()) {
2289 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2292 containerComponent = validateContainerComponentExists.left().value();
2294 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2295 if (resourceInstanceStatus.isRight()) {
2296 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2300 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2301 if (CollectionUtils.isEmpty(instanceProperties)) {
2302 instanceProperties = new ArrayList<>();
2304 resultOp = Either.left(instanceProperties);
2307 unlockComponent(resultOp, containerComponent);
2311 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2312 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2314 if (counterRes.isRight()) {
2315 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2316 StorageOperationStatus status = counterRes.right().value();
2317 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2318 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2320 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2326 * updates componentInstance modificationTime
2328 * @param componentInstance
2329 * @param componentInstanceType
2330 * @param modificationTime
2331 * @param inTransaction
2334 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2335 Either<ComponentInstanceData, ResponseFormat> result;
2336 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2338 if (updateComponentInstanceRes.isRight()) {
2339 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2340 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2342 result = Either.left(updateComponentInstanceRes.left().value());
2347 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2348 // TODO Add implementation
2349 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2353 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2354 // TODO Add implementation
2355 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2359 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2360 // TODO Add implementation
2361 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2365 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2366 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2369 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2371 Either<ComponentInstance, StorageOperationStatus> result = null;
2372 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2373 Optional<ComponentInstance> foundInstance = null;
2374 if (CollectionUtils.isEmpty(instances)) {
2375 result = Either.right(StorageOperationStatus.NOT_FOUND);
2377 if (result == null) {
2378 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2379 if (!foundInstance.isPresent()) {
2380 result = Either.right(StorageOperationStatus.NOT_FOUND);
2383 if (result == null) {
2384 result = Either.left(foundInstance.get());
2389 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2391 Long creationDate = origInstanceForUpdate.getCreationTime();
2393 Long modificationTime = System.currentTimeMillis();
2394 resourceInstanceForUpdate.setCreationTime(creationDate);
2395 resourceInstanceForUpdate.setModificationTime(modificationTime);
2397 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2399 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2400 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2403 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2405 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2406 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2408 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2409 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2411 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2412 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2414 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2415 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2417 if (resourceInstanceForUpdate.getOriginType() == null) {
2418 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2420 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2421 resourceInstanceForUpdate.setIsProxy(true);
2422 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2423 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2425 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2426 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2428 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2429 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2431 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2432 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2434 return resourceInstanceForUpdate;
2437 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2438 * @param containerComponentType
2439 * @param containerComponentId
2440 * @param componentInstanceUniqueId
2441 * @param capabilityType
2442 * @param capabilityName
2447 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2449 Component containerComponent = null;
2451 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2453 validateUserExists(userId, "Get Component Instance Properties By Id", false);
2454 if(resultOp == null){
2455 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2456 if (validateComponentType.isRight()) {
2457 resultOp = Either.right(validateComponentType.right().value());
2460 if(resultOp == null){
2461 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2462 if (validateContainerComponentExists.isRight()) {
2463 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2465 containerComponent = validateContainerComponentExists.left().value();
2468 if(resultOp == null){
2469 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2470 if (resourceInstanceStatus.isRight()) {
2471 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2473 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2478 unlockComponent(resultOp, containerComponent);
2482 private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2483 Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2484 CapabilityDefinition foundCapability;
2485 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2486 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2487 if (capabilitiesPerType != null) {
2488 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2489 if (capabilityOpt.isPresent()) {
2490 foundCapability = capabilityOpt.get();
2491 result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2495 if (result == null) {
2496 result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2501 private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2502 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2504 Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2505 if(getComponentInstanceCapabilityProperties.isRight()){
2506 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2508 resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
2510 } catch(Exception e){
2511 log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2512 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2517 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2518 String capabilityType, String capabilityName, String ownerId) {
2519 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2520 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2521 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2522 String capKey = sb.toString();
2524 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2525 .orElse(Collections.emptyMap());
2526 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2527 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2528 if (cap.isPresent()) {
2529 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2530 if (capProperties != null) {
2531 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2532 StorageOperationStatus status;
2533 if (instanceProperty.isPresent()) {
2534 instanceProperty.get().setValue(newValue);
2535 List<String> path = new ArrayList<>();
2536 path.add(componentInstanceUniqueId);
2538 instanceProperty.get().setPath(path);
2539 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2540 if (status != StorageOperationStatus.OK) {
2541 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2542 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2545 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2549 return componentsUtils.getResponseFormat(ActionStatus.OK);
2552 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2553 List<ComponentInstanceProperty> properties, String userId) {
2554 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2556 validateUserExists(userId, "update instance capability property", false);
2558 if (componentTypeEnum == null) {
2559 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2560 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2562 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2564 if (getResourceResult.isRight()) {
2565 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2566 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2568 Component containerComponent = getResourceResult.left().value();
2570 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2571 log.info("Restricted operation for user: {sourcePropList} on component {}", userId, containerComponentId);
2572 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2574 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2575 if (resourceInstanceStatus.isRight()) {
2576 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2578 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2580 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2581 if (lockStatus != StorageOperationStatus.OK) {
2582 log.debug("Failed to lock component {}", containerComponentId);
2583 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2586 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2587 if (allDataTypes.isRight()) {
2588 TitanOperationStatus status = allDataTypes.right().value();
2589 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2590 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2594 for (ComponentInstanceProperty property : properties) {
2595 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2596 newPropertyValueEither.bimap(updatedValue ->
2597 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2600 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2602 if (updateContainerRes.isRight()) {
2603 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2604 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2607 resultOp = Either.left(properties);
2611 if (resultOp == null || resultOp.isRight()) {
2612 titanDao.rollback();
2617 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2621 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2622 List<ComponentInstanceProperty> properties, String userId) {
2623 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2625 validateUserExists(userId, "update instance capability property", false);
2627 if (componentTypeEnum == null) {
2628 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2629 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2631 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2633 if (getResourceResult.isRight()) {
2634 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2635 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2637 Component containerComponent = getResourceResult.left().value();
2639 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2640 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2641 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2643 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2644 if (resourceInstanceStatus.isRight()) {
2645 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2647 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2649 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2650 if (lockStatus != StorageOperationStatus.OK) {
2651 log.debug("Failed to lock component {}", containerComponentId);
2652 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2656 for (ComponentInstanceProperty property : properties) {
2657 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2658 newPropertyValueEither.bimap(updatedValue ->
2659 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2662 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2664 if (updateContainerRes.isRight()) {
2665 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2666 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2669 resultOp = Either.left(properties);
2673 if (resultOp == null || resultOp.isRight()) {
2674 titanDao.rollback();
2679 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2683 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2684 String containerComponentId,
2685 String componentInstanceId,
2688 Map<String, ComponentInstance> resultMap = new HashMap<>();
2689 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2690 if (getOrigComponent.isRight()) {
2691 log.error("Failed to get the original component information");
2692 return Either.right(componentsUtils.getResponseFormat(
2693 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2696 Component origComponent = getOrigComponent.left().value();
2698 Either<Boolean, ResponseFormat> lockComponent = lockComponent(origComponent, "copyComponentInstance");
2699 if (lockComponent.isRight()) {
2700 log.error("destComponentInstance's data is {}", origComponent.toString());
2701 return Either.right(lockComponent.right().value());
2705 Either<ComponentInstance, ResponseFormat> actionResponse = null;
2707 actionResponse = createComponentInstance(
2708 "services", containerComponentId, userId, inputComponentInstance, true, false);
2710 if (actionResponse.isRight()) {
2711 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
2712 return Either.right(componentsUtils.getResponseFormat(
2713 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2718 // on failure of the create instance unlock the resource and rollback the transaction.
2719 if (null == actionResponse || actionResponse.isRight()) {
2720 titanDao.rollback();
2722 unlockComponent(actionResponse, origComponent);
2725 Either<String, ResponseFormat> resultOp = null;
2728 ComponentInstance destComponentInstance = actionResponse.left().value();
2729 log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2732 resultOp = deepCopyComponentInstance(
2733 origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2735 if (resultOp.isRight()) {
2736 log.error("Failed to deep copy component instance");
2737 return Either.right(componentsUtils.getResponseFormat(
2738 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2740 resultMap.put("componentInstance", destComponentInstance);
2741 return Either.left(resultMap);
2744 if (resultOp == null || resultOp.isRight()) {
2745 titanDao.rollback();
2749 log.debug("Success trasaction commit");
2752 unlockComponent(resultOp, origComponent);
2756 private Either<String, ResponseFormat> deepCopyComponentInstance(
2757 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2758 ComponentInstance destComponentInstance, String userId) {
2760 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2761 if (getDestComponent.isRight()) {
2762 log.error("Failed to get the dest component information");
2763 return Either.right(componentsUtils.getResponseFormat(
2764 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2767 Component destComponent = getDestComponent.left().value();
2769 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2770 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2771 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2772 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2773 return Either.right(componentsUtils.getResponseFormat(
2774 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2777 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2778 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2779 if (copyComponentInstanceWithAttributes.isRight()) {
2780 log.error("Failed to copy component instance with attributes as part of deep copy");
2781 return Either.right(componentsUtils.getResponseFormat(
2782 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2784 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2787 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2788 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2789 ComponentInstance destComponentInstance, String userId) {
2790 log.debug("start to copy ComponentInstance with properties and inputs");
2792 List<ComponentInstanceProperty> sourcePropList = null;
2793 if (sourceComponent.getComponentInstancesProperties() != null
2794 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2795 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2796 log.debug("sourcePropList");
2799 List<ComponentInstanceProperty> destPropList = null;
2800 String destComponentInstanceId = destComponentInstance.getUniqueId();
2801 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2802 if (destComponent.getComponentInstancesProperties() != null
2803 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2804 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2805 log.debug("destPropList {}");
2808 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2810 if (null != destPropList && null != sourcePropList) {
2811 log.debug("start to set property and attribute");
2812 for (ComponentInstanceProperty destProp : destPropList) {
2813 String destPropertyName = destProp.getName();
2814 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2815 if (!destPropertyName.equals(sourceProp.getName())) {
2818 log.debug("now set property");
2819 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2820 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2821 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2823 destProp.setValue(sourceProp.getValue());
2824 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2825 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2826 if (updatePropertyValueEither.isRight()) {
2827 log.error("Failed to copy the property {}", destPropertyName);
2828 return Either.right(componentsUtils.getResponseFormat(
2829 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2834 log.debug("Now start to update inputs");
2836 if (sourceProp.getGetInputValues() != null) {
2837 if (sourceProp.getGetInputValues().isEmpty()) {
2838 log.debug("source property input values empty");
2841 log.debug("Now starting to copy the {} property", destPropertyName);
2843 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2844 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2845 if (getSourceInputDefaultValue.isRight()) {
2846 return Either.right(getSourceInputDefaultValue.right().value());
2848 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2853 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2856 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
2857 Component destComponent,
2858 String sourceComponentInstanceId,
2859 ComponentInstance destComponentInstance,
2861 String destComponentInstanceId = destComponentInstance.getUniqueId();
2863 log.info("start to copy component instance with attributes");
2865 List<ComponentInstanceProperty> sourceAttributeList = null;
2866 if (sourceComponent.getComponentInstancesAttributes() != null
2867 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
2868 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
2869 log.info("sourceAttributes {}");
2872 List<ComponentInstanceProperty> destAttributeList = null;
2873 if (destComponent.getComponentInstancesAttributes() != null
2874 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
2875 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
2876 log.info("destAttributeList {}");
2878 if (null != sourceAttributeList && null != destAttributeList) {
2879 log.info("set attribute");
2881 for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
2882 String sourceAttributeName = sourceAttribute.getName();
2883 for (ComponentInstanceProperty destAttribute : destAttributeList) {
2884 if (sourceAttributeName.equals(destAttribute.getName())) {
2885 if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
2886 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
2888 sourceAttribute.setUniqueId(
2889 UniqueIdBuilder.buildResourceInstanceUniuqeId(
2890 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
2892 Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
2893 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
2894 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
2896 if (updateAttributeValueEither.isRight()) {
2897 log.error("Failed to copy the attribute");
2898 return Either.right(componentsUtils
2899 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
2900 "Failed to paste component instance to the canvas, attribute copy"));
2909 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2912 private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
2914 String resourceInstanceId,
2915 ComponentInstanceProperty attribute,
2918 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2920 validateUserExists(userId, "Create or Update attribute value", false);
2922 if (componentTypeEnum == null) {
2923 BeEcompErrorManager.getInstance().logInvalidInputError(
2924 "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2925 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2929 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2931 if (getResourceResult.isRight()) {
2932 log.info("Failed to retrieve component id {}", componentId);
2933 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2937 Component containerComponent = getResourceResult.left().value();
2939 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2941 if (resourceInstanceStatus.isRight()) {
2942 resultOp = Either.right(componentsUtils.getResponseFormat(
2943 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
2947 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2950 String propertyType = attribute.getType();
2951 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2952 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
2954 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2955 SchemaDefinition def = attribute.getSchema();
2957 log.info("Schema doesn't exists for attribute of type {}", type);
2958 return Either.right(componentsUtils.getResponseFormat(
2959 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2961 PropertyDataDefinition propDef = def.getProperty();
2962 if (propDef == null) {
2963 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
2964 return Either.right(componentsUtils.getResponseFormat(
2965 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2969 List<ComponentInstanceProperty> instanceAttributes = containerComponent.
2970 getComponentInstancesAttributes().get(resourceInstanceId);
2971 Optional<ComponentInstanceProperty> instanceAttribute =
2972 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
2973 StorageOperationStatus status;
2975 if (instanceAttribute.isPresent()) {
2976 log.info("updateComponentInstanceAttribute");
2977 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
2979 log.info("addComponentInstanceAttribute");
2980 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
2982 if (status != StorageOperationStatus.OK) {
2983 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2984 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2987 List<String> path = new ArrayList<>();
2988 path.add(foundResourceInstance.getUniqueId());
2989 attribute.setPath(path);
2991 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2992 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
2993 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2995 if (updateContainerRes.isRight()) {
2996 ActionStatus actionStatus = componentsUtils.
2997 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2998 resultOp = Either.right(componentsUtils.
2999 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3002 resultOp = Either.left(attribute);
3009 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3010 String componentInstanceId,
3011 ComponentInstanceProperty property) {
3012 Either<String, ResponseFormat> resultOp;
3013 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3015 if (getComponent.isRight()) {
3016 log.error("Failed to get the component information");
3017 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3018 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3021 Component containerComponent = getComponent.left().value();
3023 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3024 containerComponent, componentInstanceId, property);
3025 if (status != StorageOperationStatus.OK) {
3026 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3027 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3031 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3032 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3034 if (updateContainerRes.isRight()) {
3035 ActionStatus actionStatus = componentsUtils.
3036 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3037 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3041 return Either.left("Update OK");
3044 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3045 List<InputDefinition> inputList = component.getInputs();
3046 for (InputDefinition input : inputList) {
3047 if (input.getUniqueId().equals(inputId)) {
3048 if (input.getDefaultValue() == null) {
3049 log.debug("The input's default value is null");
3050 return Either.left(null);
3052 return Either.left(input.getDefaultValue());
3055 log.error("The input's default value with id {} is not found", inputId);
3056 return Either.right(componentsUtils.getResponseFormat(
3057 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3061 * Method to delete selected nodes and edges on composition page
3062 * @param containerComponentType
3063 * @param componentId
3064 * @param componentInstanceIdList
3068 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3070 List<String> componentInstanceIdList,
3073 List<String> deleteErrorIds = new ArrayList<>();
3074 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3075 Either<Component, ResponseFormat> validateResponse = validateUser(containerComponentType, componentId, userId);
3076 if (validateResponse.isRight()) {
3077 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3078 return deleteErrorMap;
3080 Component containerComponent = validateResponse.left().value();
3082 Either<Boolean, ResponseFormat> lockComponent = lockComponent(
3083 containerComponent, "batchDeleteComponentInstance");
3084 if (lockComponent.isRight()) {
3085 log.error("Failed to lockComponent containerComponent");
3086 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3087 return deleteErrorMap;
3091 for (String eachInstanceId : componentInstanceIdList) {
3092 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3093 containerComponent, containerComponentType, componentId, eachInstanceId);
3094 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3095 if (actionResponse.isRight()) {
3096 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3097 deleteErrorIds.add(eachInstanceId);
3100 //sending the ids of the error nodes that were not deleted to UI
3101 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3102 return deleteErrorMap;
3104 unlockComponent(validateResponse, containerComponent);
3108 private Either<Component, ResponseFormat> validateUser(String containerComponentParam,
3109 String containerComponentId,
3111 validateUserExists(userId, "delete Component Instance", false);
3112 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
3113 if (validateComponentType.isRight()) {
3114 log.error("ComponentType[{}] doesn't support", containerComponentParam);
3115 return Either.right(validateComponentType.right().value());
3118 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
3119 Either<Component, ResponseFormat> validateComponentExists = validateComponentExists(
3120 containerComponentId, containerComponentType, null);
3121 if (validateComponentExists.isRight()) {
3122 log.error("Component Id[{}] doesn't exist", containerComponentId);
3123 return Either.right(validateComponentExists.right().value());
3126 Component containerComponent = validateComponentExists.left().value();
3127 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
3128 if (validateCanWorkOnComponent.isRight()) {
3129 return Either.right(validateCanWorkOnComponent.right().value());
3131 return Either.left(containerComponent);
3134 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3135 String containerComponentType,
3136 String containerComponentId,
3137 String componentInstanceId) {
3139 Either<ComponentInstance, ResponseFormat> resultOp;
3140 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3142 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3144 if (resultOp.isRight()) {
3145 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3146 return Either.right(resultOp.right().value());
3149 log.info("Successfully deleted instance with id {}", componentInstanceId);
3150 return Either.left(resultOp.left().value());