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";
123 private IComponentInstanceOperation componentInstanceOperation;
126 private ArtifactsBusinessLogic artifactBusinessLogic;
129 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
132 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
135 private ForwardingPathOperation forwardingPathOperation;
137 public ComponentInstanceBusinessLogic() {
140 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
141 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
142 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
145 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
146 List<ComponentInstanceProperty> resList = new ArrayList<>();
147 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
148 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
149 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
151 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
153 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
155 ciName = ciOp.get().getName();
156 if (ciPropList != null && !ciPropList.isEmpty()) {
157 for(ComponentInstanceProperty prop: ciPropList){
158 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
159 if(inputsValues != null && !inputsValues.isEmpty()){
160 for(GetInputValueDataDefinition inputData: inputsValues){
161 if(isGetInputValueForInput(inputData, inputId)){
162 prop.setComponentInstanceId(s);
163 prop.setComponentInstanceName(ciName);
178 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
179 List<ComponentInstanceInput> resList = new ArrayList<>();
180 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
181 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
182 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
184 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
186 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
188 ciName = ciOp.get().getName();
189 if (ciPropList != null && !ciPropList.isEmpty()) {
190 for(ComponentInstanceInput prop: ciPropList){
191 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
192 if(inputsValues != null && !inputsValues.isEmpty()){
193 for(GetInputValueDataDefinition inputData: inputsValues){
194 if(isGetInputValueForInput(inputData, inputId)){
195 prop.setComponentInstanceId(s);
196 prop.setComponentInstanceName(ciName);
211 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
212 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
214 Component origComponent = null;
215 Either<ComponentInstance, ResponseFormat> resultOp = null;
217 org.openecomp.sdc.be.model.Component containerComponent = null;
218 ComponentTypeEnum containerComponentType;
221 user = validateUserExists(userId, "create Component Instance", inTransaction);
223 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
224 if (validateValidJson.isRight()) {
225 return Either.right(validateValidJson.right().value());
228 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
229 if (validateComponentType.isRight()) {
230 return Either.right(validateComponentType.right().value());
232 containerComponentType = validateComponentType.left().value();
235 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
236 if (validateComponentExists.isRight()) {
237 return Either.right(validateComponentExists.right().value());
239 containerComponent = validateComponentExists.left().value();
242 if (ModelConverter.isAtomicComponent(containerComponent)) {
243 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
244 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
247 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
248 if (validateCanWorkOnComponent.isRight()) {
249 return Either.right(validateCanWorkOnComponent.right().value());
252 if (resourceInstance != null && containerComponentType != null) {
253 OriginTypeEnum originType = resourceInstance.getOriginType();
254 if (originType == OriginTypeEnum.ServiceProxy) {
255 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
256 if (serviceProxyOrigin.isRight()) {
257 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
258 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
260 origComponent = serviceProxyOrigin.left().value();
262 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
263 if (fillProxyRes != StorageOperationStatus.OK) {
264 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
265 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
270 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
272 if (getOriginComponentRes.isRight()) {
273 return Either.right(getOriginComponentRes.right().value());
275 origComponent = getOriginComponentRes.left().value();
280 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
281 if (lockComponent.isRight()) {
282 return Either.right(lockComponent.right().value());
285 log.debug("Try to create entry on graph");
286 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
291 unlockComponent(resultOp, containerComponent);
295 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
296 resourceInstance.setIsProxy(true);
297 ComponentParametersView filter = new ComponentParametersView(true);
298 filter.setIgnoreCapabilities(false);
299 filter.setIgnoreCapabiltyProperties(false);
300 filter.setIgnoreComponentInstances(false);
301 filter.setIgnoreRequirements(false);
302 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
303 if (serviceRes.isRight()) {
304 return serviceRes.right().value();
306 Component service = serviceRes.left().value();
307 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
308 resourceInstance.setCapabilities(capabilities);
309 Map<String, List<RequirementDefinition>> req = service.getRequirements();
310 resourceInstance.setRequirements(req);
312 String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
313 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
314 int lastIndexOf = toscaResourceName.lastIndexOf('.');
315 if (lastIndexOf != -1) {
316 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
317 resourceInstance.setToscaComponentName(proxyToscaName);
319 resourceInstance.setName(name);
320 resourceInstance.setIsProxy(true);
321 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
322 resourceInstance.setSourceModelName(service.getName());
323 resourceInstance.setSourceModelUuid(service.getUUID());
324 resourceInstance.setSourceModelUid(service.getUniqueId());
325 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
326 resourceInstance.setDescription("A Proxy for Service " + service.getName());
327 resourceInstance.setComponentVersion(service.getVersion());
329 return StorageOperationStatus.OK;
332 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
334 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
335 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
336 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
338 User user = validateUserExists(userId, "create And Associate RI To RI", false);
340 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
341 if (validateComponentType.isRight()) {
342 return Either.right(validateComponentType.right().value());
345 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
347 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
348 if (validateComponentExists.isRight()) {
349 return Either.right(validateComponentExists.right().value());
351 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
353 if (ModelConverter.isAtomicComponent(containerComponent)) {
354 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
355 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
358 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
359 if (validateCanWorkOnComponent.isRight()) {
360 return Either.right(validateCanWorkOnComponent.right().value());
363 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
364 if (lockComponent.isRight()) {
365 return Either.right(lockComponent.right().value());
369 log.debug("Try to create entry on graph");
370 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
372 if (eitherResourceName.isRight()) {
373 resultOp = Either.right(eitherResourceName.right().value());
376 Component origComponent = eitherResourceName.left().value();
378 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
379 if (result.isRight()) {
380 log.debug("Failed to create resource instance {}", containerComponentId);
381 resultOp = Either.right(result.right().value());
386 log.debug("Entity on graph is created.");
387 ComponentInstance resResourceInfo = result.left().value();
388 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
389 associationInfo.setFromNode(resResourceInfo.getUniqueId());
391 associationInfo.setToNode(resResourceInfo.getUniqueId());
394 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
395 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
396 if (resultReqCapDef.isLeft()) {
397 log.debug("Enty on graph is created.");
398 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
399 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
400 resultOp = Either.left(resInfo);
404 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
405 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
410 unlockComponent(resultOp, containerComponent);
414 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
415 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
418 private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
419 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
422 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
423 Either<Component, ResponseFormat> eitherResponse;
424 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
425 if (eitherComponent.isRight()) {
426 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
427 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
429 eitherResponse = Either.left(eitherComponent.left().value());
431 return eitherResponse;
434 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
435 Either<ComponentInstance, ResponseFormat> resultOp;
437 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
439 if (result.isRight()) {
440 log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
441 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
445 log.debug("Entity on graph is created.");
446 Component updatedComponent = result.left().value().getLeft();
447 Map<String, String> existingEnvVersions = new HashMap<>();
448 // TODO existingEnvVersions ??
449 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
450 if (addComponentInstanceArtifacts.isRight()) {
451 log.debug("Failed to create component instance {}", componentInstance.getName());
452 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
456 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
457 if (!updatedInstanceOptional.isPresent()) {
458 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
459 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
462 resultOp = Either.left(updatedInstanceOptional.get());
467 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
468 * @param containerComponent
469 * @param componentInstance
470 * @param originComponent
472 * @param existingEnvVersions
475 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) {
477 log.debug("add artifacts to resource instance");
478 List<GroupDefinition> filteredGroups = null;
479 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
480 if (!ActionStatus.OK.equals(status)) {
481 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
482 return Either.right(resultOp);
484 StorageOperationStatus artStatus;
485 // generate heat_env if necessary
486 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
487 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
489 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
490 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
492 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
493 String type = artifact.getArtifactType();
494 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
495 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
497 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
500 if (artifact.checkEsIdExist()) {
501 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
502 componentInstance.getName(), user, containerComponent, existingEnvVersions);
503 if (createHeatEnvPlaceHolder.isRight()) {
504 return Either.right(createHeatEnvPlaceHolder.right().value());
506 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
508 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
510 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
511 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
513 if (CollectionUtils.isNotEmpty(filteredGroups)) {
514 for (GroupDefinition groupInstance : filteredGroups) {
515 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
516 if (op.isPresent()) {
517 List<ArtifactDefinition> artifactsUid;
518 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
519 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
521 artifactsUid = new ArrayList<>();
523 artifactsUid.add(artifactDefinition);
524 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
531 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
532 if (artStatus != StorageOperationStatus.OK) {
533 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
534 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
537 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
538 if (result != StorageOperationStatus.OK) {
539 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
540 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
542 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
545 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
546 if (artStatus != StorageOperationStatus.OK) {
547 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
548 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
551 componentInstance.setArtifacts(originComponent.getArtifacts());
552 return Either.left(ActionStatus.OK);
555 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
556 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
558 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
559 if (getResourceDeploymentArtifacts.isRight()) {
560 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
561 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
562 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
563 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
566 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
569 if (!deploymentArtifacts.isEmpty()) {
570 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
571 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
572 if (!artifact.getValue().checkEsIdExist()) {
573 tempDeploymentArtifacts.remove(artifact.getKey());
577 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
580 return ActionStatus.OK;
583 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
584 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
587 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
588 boolean needLock, boolean createNewTransaction) {
590 validateUserExists(userId, "update Component Instance", inTransaction);
592 Either<ComponentInstance, ResponseFormat> resultOp = null;
594 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
595 if (validateComponentType.isRight()) {
596 return Either.right(validateComponentType.right().value());
599 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
601 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
602 if (validateComponentExists.isRight()) {
603 return Either.right(validateComponentExists.right().value());
605 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
607 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
608 if (validateCanWorkOnComponent.isRight()) {
609 return Either.right(validateCanWorkOnComponent.right().value());
611 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
612 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
613 if (validateParentStatus.isRight()) {
614 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
615 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
618 if (!validateParentStatus.left().value()) {
619 resultOp = Either.right(
620 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
625 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
626 if (lockComponent.isRight()) {
627 return Either.right(lockComponent.right().value());
632 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
634 if (eitherResourceName.isRight()) {
635 resultOp = Either.right(eitherResourceName.right().value());
638 Component origComponent = eitherResourceName.left().value();
640 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
645 unlockComponent(resultOp, containerComponent);
649 // New Multiple Instance Update API
650 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
652 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
653 org.openecomp.sdc.be.model.Component containerComponent = null;
655 validateUserExists(userId, "update Component Instance", true);
657 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
658 if (validateComponentType.isRight()) {
659 return Either.right(validateComponentType.right().value());
662 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
664 ComponentParametersView componentFilter = new ComponentParametersView();
665 componentFilter.disableAll();
666 componentFilter.setIgnoreUsers(false);
667 componentFilter.setIgnoreComponentInstances(false);
668 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
669 if (validateComponentExists.isRight()) {
670 return Either.right(validateComponentExists.right().value());
673 containerComponent = validateComponentExists.left().value();
675 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
676 if (validateCanWorkOnComponent.isRight()) {
677 return Either.right(validateCanWorkOnComponent.right().value());
680 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
682 for (ComponentInstance componentInstance : componentInstanceList) {
683 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
684 if (!validateParent) {
685 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
686 containerComponentId));
693 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
694 if (lockComponent.isRight()) {
695 return Either.right(lockComponent.right().value());
699 List<ComponentInstance> updatedList = new ArrayList<>();
700 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
701 List<ComponentInstance> listForUpdate = new ArrayList<>();
702 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
703 containerComponent.setComponentInstances(componentInstanceList);
705 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
706 while (iterator.hasNext()) {
707 ComponentInstance origInst = iterator.next();
708 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
709 if (op.isPresent()) {
710 ComponentInstance updatedCi = op.get();
711 updatedCi = buildComponentInstance(updatedCi, origInst);
713 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
715 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());
716 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
720 listForUpdate.add(updatedCi);
722 listForUpdate.add(origInst);
724 containerComponent.setComponentInstances(listForUpdate);
726 if (resultOp == null) {
727 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
728 if (updateStatus.isRight()) {
729 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
730 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
733 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
734 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
735 if (op.isPresent()) {
736 updatedList.add(updatedInstance);
742 resultOp = Either.left(updatedList);
747 unlockComponent(resultOp, containerComponent);
752 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
753 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
756 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
757 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
758 return ComponentTypeEnum.SERVICE_INSTANCE;
760 return ComponentTypeEnum.RESOURCE_INSTANCE;
764 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
765 ComponentInstance componentInstance) {
767 Either<ComponentInstance, ResponseFormat> resultOp = null;
768 Optional<ComponentInstance> componentInstanceOptional = null;
769 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
770 ComponentInstance oldComponentInstance = null;
771 boolean isNameChanged = false;
773 if (resultOp == null) {
774 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
775 if (!componentInstanceOptional.isPresent()) {
776 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
777 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
780 if (resultOp == null) {
781 oldComponentInstance = componentInstanceOptional.get();
782 String newInstanceName = componentInstance.getName();
783 if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
784 isNameChanged = true;
785 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
787 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);
788 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
791 if (resultOp == null) {
792 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
793 if (updateRes.isRight()) {
794 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
795 updateRes.right().value());
796 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
798 // region - Update instance Groups
800 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
801 if (result.isRight())
802 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
807 if (resultOp == null) {
808 String newInstanceId = updateRes.left().value().getRight();
809 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
811 if (!updatedInstanceOptional.isPresent()) {
812 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
813 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
815 resultOp = Either.left(updatedInstanceOptional.get());
819 if (resultOp == null) {
820 resultOp = Either.left(componentInstanceOptional.get());
827 * The normalized old vf name
828 * @param newNormailzedPrefix-
829 * The normalized new vf name
830 * @param qualifiedGroupInstanceName-
831 * old Group Instance Name
833 // modify group names
834 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
835 if (qualifiedGroupInstanceName == null) {
836 log.info("CANNOT change group name ");
839 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
840 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
841 return qualifiedGroupInstanceName;
844 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
845 oldComponentInstance.setName(newComponentInstance.getName());
846 oldComponentInstance.setModificationTime(System.currentTimeMillis());
847 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
848 if (oldComponentInstance.getGroupInstances() != null)
849 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
850 return oldComponentInstance;
853 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
855 validateUserExists(userId, "delete Component Instance", false);
857 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
858 if (validateComponentType.isRight()) {
859 return Either.right(validateComponentType.right().value());
862 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
863 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
864 if (validateComponentExists.isRight()) {
865 return Either.right(validateComponentExists.right().value());
867 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
868 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
869 if (validateCanWorkOnComponent.isRight()) {
870 return Either.right(validateCanWorkOnComponent.right().value());
873 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
874 if (lockComponent.isRight()) {
875 return Either.right(lockComponent.right().value());
878 Either<ComponentInstance, ResponseFormat> resultOp = null;
880 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
881 if (resultOp.isRight()){
884 Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
885 containerComponentType, resultOp);
886 if (deleteEither.isRight()){
892 unlockComponent(resultOp, containerComponent);
896 public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
897 Either<ComponentInstance, ResponseFormat> resultOp) {
898 if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
899 final ComponentInstance componentInstance = resultOp.left().value();
900 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
901 if (!pathIDsToBeDeleted.isEmpty()) {
902 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
904 if(deleteForwardingPathsEither.isRight()) {
905 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
914 private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
916 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
917 if(storageStatus.isRight()) {
918 return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
920 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
921 Sets.newHashSet(pathIdsToDelete));
923 if(result.isRight()) {
924 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
926 return Either.left(result.left().value());
929 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
930 ComponentParametersView filter = new ComponentParametersView(true);
931 filter.setIgnoreForwardingPath(false);
932 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
933 .getToscaElement(containerComponentId, filter);
934 Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
935 List<String> pathIDsToBeDeleted = new ArrayList<>();
937 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
938 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
940 return pathIDsToBeDeleted;
943 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
944 String componentInstanceId){
945 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
946 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
947 elementDataDefinition.getToNode()
948 .equalsIgnoreCase(componentInstanceId));
952 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
954 Either<ComponentInstance, ResponseFormat> resultOp = null;
955 ComponentInstance deletedInstance = null;
956 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
958 if (deleteRes.isRight()) {
959 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
960 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
961 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
963 if (resultOp == null) {
964 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
965 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
966 resultOp = Either.left(deletedInstance);
968 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
969 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
970 for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
971 Map<String, String> members = currGroup.getMembers();
972 if (members != null && members.containsKey(deletedInstance.getName())) {
973 members.remove(deletedInstance.getName());
974 groupsToUpdate.add(currGroup);
977 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
978 if (updateGroupsRes.isRight()) {
979 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
980 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
981 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
984 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
985 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
986 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
987 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
988 if (deleteInputsRes != StorageOperationStatus.OK) {
989 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
990 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
997 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
998 ComponentInstance foundInstance = null;
999 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1000 if (instance.getUniqueId().equals(componentInstanceId)) {
1001 foundInstance = instance;
1002 containerComponent.getComponentInstances().remove(instance);
1006 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1007 return foundInstance;
1010 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1011 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1012 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1016 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1017 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1020 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1021 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1024 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1025 boolean createNewTransaction) {
1027 validateUserExists(userId, "associate Ri To RI", inTransaction);
1029 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1031 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1032 if (validateComponentExists.isRight()) {
1033 return Either.right(validateComponentExists.right().value());
1035 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1037 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1038 if (validateCanWorkOnComponent.isRight()) {
1039 return Either.right(validateCanWorkOnComponent.right().value());
1042 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1044 if (lockComponent.isRight()) {
1045 return Either.right(lockComponent.right().value());
1051 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1057 unlockComponent(resultOp, containerComponent);
1061 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1063 log.debug("Try to create entry on graph");
1064 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1066 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1068 if (result.isLeft()) {
1069 log.debug("Enty on graph is created.");
1070 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1071 resultOp = Either.left(requirementCapabilityRelDef);
1075 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1076 String fromNameOrId = "";
1077 String toNameOrId = "";
1078 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1079 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1081 toNameOrId = requirementDef.getFromNode();
1082 fromNameOrId = requirementDef.getFromNode();
1083 if (fromResult.isLeft()) {
1084 fromNameOrId = fromResult.left().value().getName();
1086 if (toResult.isLeft()) {
1087 toNameOrId = toResult.left().value().getName();
1090 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1098 * @param componentId
1100 * @param requirementDefList
1101 * @param componentTypeEnum
1104 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1107 List<RequirementCapabilityRelDef> requirementDefList,
1108 ComponentTypeEnum componentTypeEnum) {
1110 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1111 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1112 if (validateResponse.isRight()) {
1116 Component containerComponent = validateResponse.left().value();
1117 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1118 if (lockComponent.isRight()) {
1122 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1123 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = dissociateRIFromRI(
1124 componentId, requirementDef, containerComponent);
1126 if (actionResponse.isLeft()) {
1127 delOkResult.add(actionResponse.left().value());
1131 unlockComponent(validateResponse, containerComponent);
1136 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1137 String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1138 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1139 if(validateResponse.isRight())
1141 return Either.right(validateResponse.right().value());
1143 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = null;
1144 Component containerComponent = validateResponse.left().value();
1145 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1146 if (lockComponent.isRight()) {
1147 return Either.right(lockComponent.right().value());
1150 actionResponse = dissociateRIFromRI(
1151 componentId, requirementDef,containerComponent);
1153 unlockComponent(validateResponse, containerComponent);
1155 return actionResponse;
1158 private Either<Component, ResponseFormat> validateDissociateRI(
1159 String componentId, String userId, ComponentTypeEnum componentTypeEnum) {
1160 validateUserExists(userId, "dissociate RI From RI", false);
1163 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1164 if (validateComponentExists.isRight()) {
1165 return Either.right(validateComponentExists.right().value());
1167 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1169 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1170 if (validateCanWorkOnComponent.isRight()) {
1171 return Either.right(validateCanWorkOnComponent.right().value());
1173 return Either.left(containerComponent);
1176 private Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1177 String componentId, RequirementCapabilityRelDef requirementDef, Component containerComponent) {
1179 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1180 log.debug("Try to create entry on graph");
1181 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(
1182 componentId, requirementDef);
1183 if (result.isLeft()) {
1184 log.debug("Enty on graph is created.");
1185 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1186 resultOp = Either.left(requirementCapabilityRelDef);
1191 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1192 String fromNameOrId = "";
1193 String toNameOrId = "";
1194 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(
1195 containerComponent, requirementDef.getFromNode());
1196 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(
1197 containerComponent, requirementDef.getToNode());
1199 toNameOrId = requirementDef.getFromNode();
1200 fromNameOrId = requirementDef.getFromNode();
1201 if (fromResult.isLeft()) {
1202 fromNameOrId = fromResult.left().value().getName();
1204 if (toResult.isLeft()) {
1205 toNameOrId = toResult.left().value().getName();
1209 .right(componentsUtils.getResponseFormat(
1210 componentsUtils.convertFromStorageResponseForResourceInstance(
1211 result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1217 * Allows to get relation contained in specified component according to received Id
1218 * @param componentId
1221 * @param componentTypeEnum
1224 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1226 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1228 org.openecomp.sdc.be.model.Component containerComponent = null;
1229 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1230 RequirementCapabilityRelDef foundRelation = null;
1232 validateUserExists(userId, "get relation by Id", false);
1234 if(resultOp == null){
1235 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1236 if (validateComponentExists.isRight()) {
1237 resultOp = Either.right(validateComponentExists.right().value());
1240 if(resultOp == null){
1241 containerComponent = validateComponentExists.left().value();
1242 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1243 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1244 if(foundRelation == null){
1245 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1246 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1247 resultOp = Either.right(responseFormat);
1250 if(resultOp == null){
1251 resultOp = setRelatedCapability(foundRelation, containerComponent);
1253 if(resultOp.isLeft()){
1254 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1256 } catch (Exception e) {
1257 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1258 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1263 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1264 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1265 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1266 return relationship;
1272 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1273 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1274 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1275 String instanceId = foundRelation.getFromNode();
1276 Optional<RequirementDefinition> foundRequirement;
1277 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1278 if(!instance.isPresent()){
1279 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1280 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1281 result = Either.right(responseFormat);
1284 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1285 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1286 if(foundRequirement.isPresent()){
1287 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1288 result = Either.left(foundRelation);
1293 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1294 if(getfulfilledRequirementRes.isRight()){
1295 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1296 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1297 result = Either.right(responseFormat);
1299 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1303 result = Either.left(foundRelation);
1308 private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1309 return req.getName().equals(relationshipInfo.getRequirement()) &&
1310 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1311 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1314 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1315 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1316 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1317 String instanceId = foundRelation.getToNode();
1318 Optional<CapabilityDefinition> foundCapability;
1319 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1320 if(!instance.isPresent()){
1321 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1322 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1323 result = Either.right(responseFormat);
1326 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1327 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1328 if(foundCapability.isPresent()){
1329 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1330 result = Either.left(foundRelation);
1335 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1336 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1337 if(getfulfilledRequirementRes.isRight()){
1338 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1339 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1340 result = Either.right(responseFormat);
1342 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1346 result = Either.left(foundRelation);
1351 private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1352 return cap.getName().equals(relationshipInfo.getCapability()) &&
1353 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1354 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1357 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1358 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1359 Either<ComponentInstanceProperty, ResponseFormat> result;
1360 if (eitherAttribute.isLeft()) {
1361 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1362 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1364 result = Either.left(instanceAttribute);
1367 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1369 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1371 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1377 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1379 Either<ComponentInstanceProperty, ResponseFormat> result;
1381 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1382 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1383 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1385 if (!errorWrapper.isEmpty()) {
1386 result = Either.right(errorWrapper.getInnerElement());
1388 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1389 if (eitherAttribute.isLeft()) {
1390 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1391 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1392 result = Either.left(instanceAttribute);
1395 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1397 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1398 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1406 * Create Or Updates Attribute Instance
1408 * @param componentTypeEnum
1409 * @param componentId
1410 * @param resourceInstanceId
1415 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1416 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1417 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1419 validateUserExist(userId, "create Or Update Attribute Value");
1420 if (errorWrapper.isEmpty()) {
1421 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1423 if (errorWrapper.isEmpty()) {
1424 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1426 if (errorWrapper.isEmpty()) {
1427 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1431 if (errorWrapper.isEmpty()) {
1432 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1434 result = createAttributeValue(attribute, resourceInstanceId);
1436 result = updateAttributeValue(attribute, resourceInstanceId);
1439 result = Either.right(errorWrapper.getInnerElement());
1445 if (result == null || result.isRight()) {
1446 titanDao.rollback();
1451 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1455 private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1456 return StringUtils.isNotEmpty(property.getValue())
1457 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1458 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1461 // US833308 VLI in service - specific network_role property value logic
1462 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1463 for (ComponentInstanceProperty property: properties) {
1464 if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1465 ComponentParametersView componentParametersView = new ComponentParametersView();
1466 componentParametersView.disableAll();
1467 componentParametersView.setIgnoreComponentInstances(false);
1468 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1469 if (getServiceResult.isRight()) {
1470 return getServiceResult.right().value();
1472 Component service = getServiceResult.left().value();
1473 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1474 if (!getInstance.isPresent()) {
1475 return StorageOperationStatus.NOT_FOUND;
1477 String prefix = service.getSystemName() + ".";
1478 String value = property.getValue();
1479 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1480 property.setValue(prefix + value);
1484 return StorageOperationStatus.OK;
1487 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1489 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1491 /*-------------------------------Validations---------------------------------*/
1493 validateUserExists(userId, "create Or Update Properties Values", false);
1495 if (componentTypeEnum == null) {
1496 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO);
1497 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1500 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1502 if (getResourceResult.isRight()) {
1503 log.debug("Failed to retrieve component, component id {}", componentId);
1504 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1507 Component containerComponent = getResourceResult.left().value();
1509 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1510 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1511 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1514 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1515 if (resourceInstanceStatus.isRight()) {
1516 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1519 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1520 // specific property value logic US833308
1521 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1522 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1523 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1527 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1528 if (lockStatus != StorageOperationStatus.OK) {
1529 log.debug("Failed to lock service {}", componentId);
1530 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1535 for (ComponentInstanceProperty property: properties) {
1536 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1537 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1538 responseFormat -> Either.right(responseFormat));
1541 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1542 if (updateContainerRes.isRight()) {
1543 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1544 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1547 resultOp = Either.left(properties);
1551 if (resultOp == null || resultOp.isRight()) {
1552 titanDao.rollback();
1557 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1561 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1562 String capabilityType, String capabilityName) {
1563 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1564 StringBuffer sb = new StringBuffer(componentInstanceUniqueId);
1565 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1566 String capKey = sb.toString();
1568 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1569 .orElse(Collections.emptyMap());
1570 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1571 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1572 if (cap.isPresent()) {
1573 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1574 if (capProperties != null) {
1575 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1576 StorageOperationStatus status;
1577 if (instanceProperty.isPresent()) {
1578 instanceProperty.get().setValue(newValue);
1579 List<String> path = new ArrayList<>();
1580 path.add(componentInstanceUniqueId);
1582 instanceProperty.get().setPath(path);
1583 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1584 if (status != StorageOperationStatus.OK) {
1585 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1586 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1589 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1595 return componentsUtils.getResponseFormat(ActionStatus.OK);
1598 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1599 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1600 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1601 StorageOperationStatus status;
1602 instanceProperty.get().setValue(newValue);
1603 if (instanceProperty.isPresent()) {
1604 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1606 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1608 if (status != StorageOperationStatus.OK) {
1609 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1610 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1612 List<String> path = new ArrayList<>();
1613 path.add(foundResourceInstance.getUniqueId());
1614 property.setPath(path);
1616 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1617 return componentsUtils.getResponseFormat(ActionStatus.OK);
1620 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1621 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1622 if (allDataTypesEither.isRight()) {
1623 TitanOperationStatus status = allDataTypesEither.right().value();
1624 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1625 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1627 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1628 String innerType = null;
1629 String propertyType = property.getType();
1630 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1631 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1633 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1634 SchemaDefinition def = property.getSchema();
1636 log.debug("Schema doesn't exists for property of type {}", type);
1637 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1639 PropertyDataDefinition propDef = def.getProperty();
1640 if (propDef == null) {
1641 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1642 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1644 innerType = propDef.getType();
1646 // Specific Update Logic
1647 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1648 String newValue = property.getValue();
1649 if (isValid.isRight()) {
1650 Boolean res = isValid.right().value();
1652 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1655 Object object = isValid.left().value();
1656 if (object != null) {
1657 newValue = object.toString();
1661 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1662 if (pair.getRight() != null && pair.getRight() == false) {
1663 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1664 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1667 return Either.left(newValue);
1670 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1671 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1672 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1673 StorageOperationStatus status;
1674 if (instanceProperty.isPresent()) {
1675 instanceProperty.get().setValue(input.getValue());
1676 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1678 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1680 if (status != StorageOperationStatus.OK) {
1681 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1682 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1684 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1685 return componentsUtils.getResponseFormat(ActionStatus.OK);
1688 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1690 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1692 validateUserExists(userId, "create Or Update Property Value", false);
1694 if (componentTypeEnum == null) {
1695 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1696 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1699 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1701 if (getResourceResult.isRight()) {
1702 log.debug("Failed to retrieve component, component id {}", componentId);
1703 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1706 Component containerComponent = getResourceResult.left().value();
1708 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1709 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1710 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1713 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1714 if (resourceInstanceStatus.isRight()) {
1715 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1719 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1722 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1723 if (lockStatus != StorageOperationStatus.OK) {
1724 log.debug("Failed to lock service {}", componentId);
1725 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1729 for (ComponentInstanceInput input: inputs) {
1730 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1731 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1732 responseFormat -> Either.right(responseFormat));
1735 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1737 if (updateContainerRes.isRight()) {
1738 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1739 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1742 resultOp = Either.left(inputs);
1746 if (resultOp == null || resultOp.isRight()) {
1747 titanDao.rollback();
1752 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1757 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1760 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1762 validateUserExists(userId, "create Or Update Property Value", false);
1764 if (componentTypeEnum == null) {
1765 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1766 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1770 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1771 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1772 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1776 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1777 if (lockStatus != StorageOperationStatus.OK) {
1778 log.debug("Failed to lock service {}", componentId);
1779 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1783 String propertyValueUid = property.getValueUniqueUid();
1785 if (propertyValueUid == null) {
1787 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1789 if (counterRes.isRight()) {
1790 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1791 StorageOperationStatus status = counterRes.right().value();
1792 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1793 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1795 Integer index = counterRes.left().value();
1796 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1798 if (result.isLeft()) {
1799 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1800 ComponentInstanceProperty instanceProperty = result.left().value();
1802 resultOp = Either.left(instanceProperty);
1805 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1807 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1809 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1813 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1815 if (result.isLeft()) {
1816 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1817 ComponentInstanceProperty instanceProperty = result.left().value();
1819 resultOp = Either.left(instanceProperty);
1822 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1824 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1826 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1829 if (resultOp.isLeft()) {
1830 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1831 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1832 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1834 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1841 if (resultOp == null || resultOp.isRight()) {
1842 titanDao.rollback();
1847 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1852 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1854 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1856 validateUserExists(userId, "create Or Update Input Value", false);
1858 if (componentTypeEnum == null) {
1859 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1860 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1864 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1865 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1866 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1870 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1871 if (lockStatus != StorageOperationStatus.OK) {
1872 log.debug("Failed to lock service {}", componentId);
1873 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1877 String propertyValueUid = inputProperty.getValueUniqueUid();
1878 if (propertyValueUid == null) {
1880 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1882 if (counterRes.isRight()) {
1883 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1884 StorageOperationStatus status = counterRes.right().value();
1885 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1886 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1888 Integer index = counterRes.left().value();
1889 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1891 if (result.isLeft()) {
1892 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1893 ComponentInstanceInput instanceProperty = result.left().value();
1895 resultOp = Either.left(instanceProperty);
1899 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1901 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1903 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1909 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1911 if (result.isLeft()) {
1912 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1913 ComponentInstanceInput instanceProperty = result.left().value();
1915 resultOp = Either.left(instanceProperty);
1919 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1921 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1923 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1930 if (resultOp == null || resultOp.isRight()) {
1931 titanDao.rollback();
1936 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1941 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1943 validateUserExists(userId, "delete Property Value", false);
1945 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1947 if (componentTypeEnum == null) {
1948 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1949 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1953 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1954 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1955 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1959 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1960 if (lockStatus != StorageOperationStatus.OK) {
1961 log.debug("Failed to lock service {}", serviceId);
1962 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1966 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1968 if (result.isLeft()) {
1969 log.debug("Property value {} was removed from graph.", propertyValueId);
1970 ComponentInstanceProperty instanceProperty = result.left().value();
1972 resultOp = Either.left(instanceProperty);
1976 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1978 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1980 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1986 if (resultOp == null || resultOp.isRight()) {
1987 titanDao.rollback();
1992 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1997 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1999 Either<Component, ResponseFormat> eitherResponse = null;
2000 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
2001 Component component;
2002 ResponseFormat errorResponse;
2003 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2004 if (getComponentRes.isRight()) {
2005 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2006 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2007 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2008 eitherResponse = Either.right(errorResponse);
2010 if (eitherResponse == null) {
2011 component = getComponentRes.left().value();
2012 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2013 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2014 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
2015 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
2016 eitherResponse = Either.right(errorResponse);
2019 if (eitherResponse == null) {
2020 eitherResponse = Either.left(getComponentRes.left().value());
2022 return eitherResponse;
2025 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2026 String containerComponentId,
2027 String componentInstanceId,
2028 ComponentInstance newComponentInstance) {
2029 Either<Set<String>, ResponseFormat> resultOp;
2030 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2031 if (validateComponentType.isRight()) {
2032 return Either.right(validateComponentType.right().value());
2034 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2035 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2038 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
2039 validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2040 if (validateComponentExists.isRight()) {
2041 return Either.right(validateComponentExists.right().value());
2043 Component containerComponent = validateComponentExists.left().value();
2045 //Fetch current component instance
2046 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2047 getResourceInstanceById(containerComponent, componentInstanceId);
2048 if (eitherResourceInstance.isRight()) {
2049 resultOp = Either.right(componentsUtils.getResponseFormat(
2050 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2053 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2055 //Check whether new componentInstance exists
2056 String resourceId = newComponentInstance.getComponentUid();
2057 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2058 if (componentExistsRes.isRight()) {
2059 log.debug("Failed to find resource {} ", resourceId);
2060 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2061 (componentExistsRes.right().value()), resourceId));
2063 } else if (!componentExistsRes.left().value()) {
2064 log.debug("The resource {} not found ", resourceId);
2065 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2069 //Fetch component using new component instance uid
2070 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2071 if (eitherResourceName.isRight()) {
2072 resultOp = Either.right(eitherResourceName.right().value());
2075 Component updatedContainerComponent=eitherResourceName.left().value();
2076 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2077 currentResourceInstance, updatedContainerComponent);
2078 resultOp=Either.left(toDeleteForwardingPaths);
2083 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2084 Component updatedContainerComponent) {
2085 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2086 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2088 Service service = (Service) containerComponent;
2089 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2091 return forwardingPathUtils.
2092 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2095 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2096 ComponentParametersView componentParametersView = new ComponentParametersView();
2097 componentParametersView.setIgnoreCapabiltyProperties(false);
2098 componentParametersView.setIgnoreForwardingPath(false);
2099 return componentParametersView;
2102 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2104 User user = validateUserExists(userId, "change Component Instance Version", false);
2106 Either<ComponentInstance, ResponseFormat> resultOp = null;
2108 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2109 if (validateComponentType.isRight()) {
2110 return Either.right(validateComponentType.right().value());
2113 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2114 ComponentParametersView componentParametersView = new ComponentParametersView();
2115 componentParametersView.setIgnoreCapabiltyProperties(false);
2116 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2117 if (validateComponentExists.isRight()) {
2118 return Either.right(validateComponentExists.right().value());
2120 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2122 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2123 if (validateCanWorkOnComponent.isRight()) {
2124 return Either.right(validateCanWorkOnComponent.right().value());
2127 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2128 if (resourceInstanceStatus.isRight()) {
2129 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2133 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2135 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2138 public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2139 ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
2140 Either<ComponentInstance, ResponseFormat> resultOp = null;
2141 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2143 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2144 String containerComponentId = containerComponent.getUniqueId();
2145 String componentInstanceId = currentResourceInstance.getUniqueId();
2146 if (lockComponent.isRight()) {
2147 return Either.right(lockComponent.right().value());
2153 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2154 resultOp = Either.left(currentResourceInstance);
2158 String resourceId = newComponentInstance.getComponentUid();
2162 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2163 if (componentExistsRes.isRight()) {
2164 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2165 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2167 } else if (!componentExistsRes.left().value()) {
2168 log.debug("The resource {} not found ", resourceId);
2169 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2173 Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2175 if (eitherOriginComponent.isRight()) {
2176 resultOp = Either.right(eitherOriginComponent.right().value());
2179 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2180 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2181 if (resultOp.isRight()) {
2182 log.debug("failed to delete resource instance {}", resourceId);
2185 ComponentInstance resResourceInfo = resultOp.left().value();
2186 Component origComponent = null;
2187 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2188 if (originType == OriginTypeEnum.ServiceProxy) {
2189 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2190 if (serviceProxyOrigin.isRight()) {
2191 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2192 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2194 origComponent = serviceProxyOrigin.left().value();
2196 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2198 if (fillProxyRes != StorageOperationStatus.OK) {
2199 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2200 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2203 newComponentInstance.setOriginType(originType);
2207 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2209 if (eitherResourceName.isRight()) {
2210 resultOp = Either.right(eitherResourceName.right().value());
2214 origComponent = eitherResourceName.left().value();
2216 newComponentInstance.setName(resResourceInfo.getName());
2219 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2220 newComponentInstance.setPosX(resResourceInfo.getPosX());
2221 newComponentInstance.setPosY(resResourceInfo.getPosY());
2222 newComponentInstance.setDescription(resResourceInfo.getDescription());
2224 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2226 if (resultOp.isRight()) {
2227 log.debug("failed to create resource instance {}", resourceId);
2231 ComponentInstance updatedComponentInstance = resultOp.left().value();
2232 if (resultOp.isRight()) {
2233 log.debug("failed to create resource instance {}", resourceId);
2237 Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2238 if (mergeStatusEither.isRight()) {
2239 return Either.right(mergeStatusEither.right().value());
2242 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2243 if (postChangeVersionResult != ActionStatus.OK) {
2244 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2247 ComponentParametersView filter = new ComponentParametersView(true);
2248 filter.setIgnoreComponentInstances(false);
2249 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2250 if (updatedComponentRes.isRight()) {
2251 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2252 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2253 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2254 log.debug("Component with id {} was not found", containerComponentId);
2255 return Either.right(responseFormat);
2257 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2258 if (resourceInstanceStatus.isRight()) {
2259 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2262 resultOp = Either.left(resourceInstanceStatus.left().value());
2266 unlockComponent(resultOp, containerComponent);
2271 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2272 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2273 Component containerComponent = null;
2275 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2277 validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2279 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2280 if (validateComponentType.isRight()) {
2281 resultOp = Either.right(validateComponentType.right().value());
2285 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2286 if (validateContainerComponentExists.isRight()) {
2287 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2290 containerComponent = validateContainerComponentExists.left().value();
2292 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2293 if (resourceInstanceStatus.isRight()) {
2294 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2298 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2299 if (CollectionUtils.isEmpty(instanceProperties)) {
2300 instanceProperties = new ArrayList<>();
2302 resultOp = Either.left(instanceProperties);
2305 unlockComponent(resultOp, containerComponent);
2309 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2310 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2312 if (counterRes.isRight()) {
2313 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2314 StorageOperationStatus status = counterRes.right().value();
2315 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2316 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2318 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2324 * updates componentInstance modificationTime
2326 * @param componentInstance
2327 * @param componentInstanceType
2328 * @param modificationTime
2329 * @param inTransaction
2332 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2333 Either<ComponentInstanceData, ResponseFormat> result;
2334 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2336 if (updateComponentInstanceRes.isRight()) {
2337 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2338 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2340 result = Either.left(updateComponentInstanceRes.left().value());
2345 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2346 // TODO Add implementation
2347 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2351 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2352 // TODO Add implementation
2353 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2357 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2358 // TODO Add implementation
2359 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2363 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2364 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2367 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2369 Either<ComponentInstance, StorageOperationStatus> result = null;
2370 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2371 Optional<ComponentInstance> foundInstance = null;
2372 if (CollectionUtils.isEmpty(instances)) {
2373 result = Either.right(StorageOperationStatus.NOT_FOUND);
2375 if (result == null) {
2376 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2377 if (!foundInstance.isPresent()) {
2378 result = Either.right(StorageOperationStatus.NOT_FOUND);
2381 if (result == null) {
2382 result = Either.left(foundInstance.get());
2387 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2389 Long creationDate = origInstanceForUpdate.getCreationTime();
2391 Long modificationTime = System.currentTimeMillis();
2392 resourceInstanceForUpdate.setCreationTime(creationDate);
2393 resourceInstanceForUpdate.setModificationTime(modificationTime);
2395 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2397 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2398 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2401 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2403 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2404 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2406 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2407 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2409 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2410 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2412 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2413 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2415 if (resourceInstanceForUpdate.getOriginType() == null) {
2416 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2418 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2419 resourceInstanceForUpdate.setIsProxy(true);
2420 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2421 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2423 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2424 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2426 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2427 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2429 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2430 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2432 return resourceInstanceForUpdate;
2435 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2436 * @param containerComponentType
2437 * @param containerComponentId
2438 * @param componentInstanceUniqueId
2439 * @param capabilityType
2440 * @param capabilityName
2445 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2447 Component containerComponent = null;
2449 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2451 validateUserExists(userId, "Get Component Instance Properties By Id", false);
2452 if(resultOp == null){
2453 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2454 if (validateComponentType.isRight()) {
2455 resultOp = Either.right(validateComponentType.right().value());
2458 if(resultOp == null){
2459 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2460 if (validateContainerComponentExists.isRight()) {
2461 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2463 containerComponent = validateContainerComponentExists.left().value();
2466 if(resultOp == null){
2467 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2468 if (resourceInstanceStatus.isRight()) {
2469 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2471 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2476 unlockComponent(resultOp, containerComponent);
2480 private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2481 Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2482 CapabilityDefinition foundCapability;
2483 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2484 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2485 if (capabilitiesPerType != null) {
2486 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2487 if (capabilityOpt.isPresent()) {
2488 foundCapability = capabilityOpt.get();
2489 result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2493 if (result == null) {
2494 result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2499 private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2500 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2502 Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2503 if(getComponentInstanceCapabilityProperties.isRight()){
2504 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2506 resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
2508 } catch(Exception e){
2509 log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2510 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2515 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2516 String capabilityType, String capabilityName, String ownerId) {
2517 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2518 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2519 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2520 String capKey = sb.toString();
2522 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2523 .orElse(Collections.emptyMap());
2524 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2525 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2526 if (cap.isPresent()) {
2527 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2528 if (capProperties != null) {
2529 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2530 StorageOperationStatus status;
2531 if (instanceProperty.isPresent()) {
2532 instanceProperty.get().setValue(newValue);
2533 List<String> path = new ArrayList<>();
2534 path.add(componentInstanceUniqueId);
2536 instanceProperty.get().setPath(path);
2537 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2538 if (status != StorageOperationStatus.OK) {
2539 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2540 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2543 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2547 return componentsUtils.getResponseFormat(ActionStatus.OK);
2550 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2551 List<ComponentInstanceProperty> properties, String userId) {
2552 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2554 validateUserExists(userId, "update instance capability property", false);
2556 if (componentTypeEnum == null) {
2557 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2558 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2560 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2562 if (getResourceResult.isRight()) {
2563 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2564 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2566 Component containerComponent = getResourceResult.left().value();
2568 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2569 log.info("Restricted operation for user: {sourcePropList} on component {}", userId, containerComponentId);
2570 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2572 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2573 if (resourceInstanceStatus.isRight()) {
2574 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2576 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2578 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2579 if (lockStatus != StorageOperationStatus.OK) {
2580 log.debug("Failed to lock component {}", containerComponentId);
2581 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2584 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2585 if (allDataTypes.isRight()) {
2586 TitanOperationStatus status = allDataTypes.right().value();
2587 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2588 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2592 for (ComponentInstanceProperty property : properties) {
2593 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2594 newPropertyValueEither.bimap(updatedValue ->
2595 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2596 responseFormat -> Either.right(responseFormat));
2598 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2600 if (updateContainerRes.isRight()) {
2601 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2602 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2605 resultOp = Either.left(properties);
2609 if (resultOp == null || resultOp.isRight()) {
2610 titanDao.rollback();
2615 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2619 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2620 List<ComponentInstanceProperty> properties, String userId) {
2621 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2623 validateUserExists(userId, "update instance capability property", false);
2625 if (componentTypeEnum == null) {
2626 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2627 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2629 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2631 if (getResourceResult.isRight()) {
2632 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2633 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2635 Component containerComponent = getResourceResult.left().value();
2637 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2638 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2639 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2641 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2642 if (resourceInstanceStatus.isRight()) {
2643 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2645 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2647 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2648 if (lockStatus != StorageOperationStatus.OK) {
2649 log.debug("Failed to lock component {}", containerComponentId);
2650 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2654 for (ComponentInstanceProperty property : properties) {
2655 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2656 newPropertyValueEither.bimap(updatedValue ->
2657 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2658 responseFormat -> Either.right(responseFormat));
2660 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2662 if (updateContainerRes.isRight()) {
2663 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2664 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2667 resultOp = Either.left(properties);
2671 if (resultOp == null || resultOp.isRight()) {
2672 titanDao.rollback();
2677 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2681 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2682 String containerComponentId,
2683 String componentInstanceId,
2686 Map<String, ComponentInstance> resultMap = new HashMap<>();
2687 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2688 if (getOrigComponent.isRight()) {
2689 log.error("Failed to get the original component information");
2690 return Either.right(componentsUtils.getResponseFormat(
2691 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2694 Component origComponent = getOrigComponent.left().value();
2696 Either<Boolean, ResponseFormat> lockComponent = lockComponent(origComponent, "copyComponentInstance");
2697 if (lockComponent.isRight()) {
2698 log.error("destComponentInstance's data is {}", origComponent.toString());
2699 return Either.right(lockComponent.right().value());
2703 Either<ComponentInstance, ResponseFormat> actionResponse = null;
2705 actionResponse = createComponentInstance(
2706 "services", containerComponentId, userId, inputComponentInstance, true, false);
2712 // on failure of the create instance unlock the resource and rollback the transaction.
2713 if (null== actionResponse || actionResponse.isRight()) {
2714 titanDao.rollback();
2715 log.error("Failed to copy the component instance to the canvas");
2717 unlockComponent(actionResponse, origComponent);
2719 return Either.right(componentsUtils.getResponseFormat(
2720 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
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 resultMap.put("componentInstance", destComponentInstance);
2739 unlockComponent(resultOp, origComponent);
2741 if (resultOp == null || resultOp.isRight()) {
2742 titanDao.rollback();
2743 log.error("Failed to deep copy component instance");
2744 return Either.right(componentsUtils.getResponseFormat(
2745 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2748 log.debug("Success trasaction commit");
2752 return Either.left(resultMap);
2755 private Either<String, ResponseFormat> deepCopyComponentInstance(
2756 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2757 ComponentInstance destComponentInstance, String userId) {
2759 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2760 if (getDestComponent.isRight()) {
2761 log.error("Failed to get the dest component information");
2762 return Either.right(componentsUtils.getResponseFormat(
2763 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2766 Component destComponent = getDestComponent.left().value();
2768 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2769 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2770 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2771 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2772 return Either.right(componentsUtils.getResponseFormat(
2773 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2776 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2777 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2778 if (copyComponentInstanceWithAttributes.isRight()) {
2779 log.error("Failed to copy component instance with attributes as part of deep copy");
2780 return Either.right(componentsUtils.getResponseFormat(
2781 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2783 return Either.left("Copy component Instance OK");
2786 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2787 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2788 ComponentInstance destComponentInstance, String userId) {
2789 log.debug("start to copy ComponentInstance with properties and inputs");
2791 List<ComponentInstanceProperty> sourcePropList = null;
2792 if (sourceComponent.getComponentInstancesProperties() != null
2793 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2794 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2795 log.debug("sourcePropList");
2798 List<ComponentInstanceProperty> destPropList = null;
2799 String destComponentInstanceId = destComponentInstance.getUniqueId();
2800 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2801 if (destComponent.getComponentInstancesProperties() != null
2802 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2803 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2804 log.debug("destPropList {}");
2807 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2809 if (null != destPropList && null != sourcePropList) {
2810 log.debug("start to set property and attribute");
2811 for (ComponentInstanceProperty destProp : destPropList) {
2812 String destPropertyName = destProp.getName();
2813 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2814 if (!destPropertyName.equals(sourceProp.getName())) {
2817 log.debug("now set property");
2818 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2819 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2820 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2822 destProp.setValue(sourceProp.getValue());
2823 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2824 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2825 if (updatePropertyValueEither.isRight()) {
2826 log.error("Failed to copy the property {}", destPropertyName);
2827 return Either.right(componentsUtils.getResponseFormat(
2828 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2833 log.debug("Now start to update inputs");
2835 if (sourceProp.getGetInputValues() != null) {
2836 if (sourceProp.getGetInputValues().size() < 1) {
2837 log.debug("property is return from input, set by man");
2840 log.debug("Now starting to copy the {} property", destPropertyName);
2842 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2843 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2844 if (getSourceInputDefaultValue.isRight()) {
2845 return Either.right(getSourceInputDefaultValue.right().value());
2847 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2852 return Either.left("Copy component Instance OK");
2855 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
2856 Component destComponent,
2857 String sourceComponentInstanceId,
2858 ComponentInstance destComponentInstance,
2860 String destComponentInstanceId = destComponentInstance.getUniqueId();
2862 log.info("start to copy component instance with attributes");
2864 List<ComponentInstanceProperty> sourceAttributeList = null;
2865 if (sourceComponent.getComponentInstancesAttributes() != null
2866 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
2867 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
2868 log.info("sourceAttributes {}");
2871 List<ComponentInstanceProperty> destAttributeList = null;
2872 if (destComponent.getComponentInstancesAttributes() != null
2873 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
2874 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
2875 log.info("destAttributeList {}");
2877 if (null != sourceAttributeList && null != destAttributeList) {
2878 log.info("set attribute");
2880 for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
2881 String sourceAttributeName = sourceAttribute.getName();
2882 for (ComponentInstanceProperty destAttribute : destAttributeList) {
2883 if (sourceAttributeName.equals(destAttribute.getName())) {
2884 if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
2885 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
2887 sourceAttribute.setUniqueId(
2888 UniqueIdBuilder.buildResourceInstanceUniuqeId(
2889 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
2891 Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
2892 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
2893 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
2895 if (updateAttributeValueEither.isRight()) {
2896 log.error("Failed to copy the attribute");
2897 return Either.right(componentsUtils
2898 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
2899 "Failed to paste component instance to the canvas, attribute copy"));
2908 return Either.left("Copy component Instance OK");
2911 private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
2913 String resourceInstanceId,
2914 ComponentInstanceProperty attribute,
2917 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2919 validateUserExists(userId, "Create or Update attribute value", false);
2921 if (componentTypeEnum == null) {
2922 BeEcompErrorManager.getInstance().logInvalidInputError(
2923 "createOrUpdateAttributeValue", "invalid component type", ErrorSeverity.INFO);
2924 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2928 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2930 if (getResourceResult.isRight()) {
2931 log.info("Failed to retrieve component id {}", componentId);
2932 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2936 Component containerComponent = getResourceResult.left().value();
2938 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2940 if (resourceInstanceStatus.isRight()) {
2941 resultOp = Either.right(componentsUtils.getResponseFormat(
2942 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
2946 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2949 String propertyType = attribute.getType();
2950 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2951 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
2953 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2954 SchemaDefinition def = attribute.getSchema();
2956 log.info("Schema doesn't exists for attribute of type {}", type);
2957 return Either.right(componentsUtils.getResponseFormat(
2958 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2960 PropertyDataDefinition propDef = def.getProperty();
2961 if (propDef == null) {
2962 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
2963 return Either.right(componentsUtils.getResponseFormat(
2964 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2968 List<ComponentInstanceProperty> instanceAttributes = containerComponent.
2969 getComponentInstancesAttributes().get(resourceInstanceId);
2970 Optional<ComponentInstanceProperty> instanceAttribute =
2971 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
2972 StorageOperationStatus status;
2974 if (instanceAttribute.isPresent()) {
2975 log.info("updateComponentInstanceAttribute");
2976 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
2978 log.info("addComponentInstanceAttribute");
2979 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
2981 if (status != StorageOperationStatus.OK) {
2982 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2983 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2986 List<String> path = new ArrayList<>();
2987 path.add(foundResourceInstance.getUniqueId());
2988 attribute.setPath(path);
2990 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2991 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
2992 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2994 if (updateContainerRes.isRight()) {
2995 ActionStatus actionStatus = componentsUtils.
2996 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2997 resultOp = Either.right(componentsUtils.
2998 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3001 resultOp = Either.left(attribute);
3008 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3009 String componentInstanceId,
3010 ComponentInstanceProperty property) {
3011 Either<String, ResponseFormat> resultOp;
3012 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3014 if (getComponent.isRight()) {
3015 log.error("Failed to get the component information");
3016 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3017 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3020 Component containerComponent = getComponent.left().value();
3022 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3023 containerComponent, componentInstanceId, property);
3024 if (status != StorageOperationStatus.OK) {
3025 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3026 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3030 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3031 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3033 if (updateContainerRes.isRight()) {
3034 ActionStatus actionStatus = componentsUtils.
3035 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3036 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3040 return Either.left("Update OK");
3043 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3044 List<InputDefinition> inputList = component.getInputs();
3045 for (InputDefinition input : inputList) {
3046 if (input.getUniqueId().equals(inputId)) {
3047 if (input.getDefaultValue() == null) {
3048 log.debug("The input's default value is null");
3049 return Either.left(null);
3051 return Either.left(input.getDefaultValue());
3054 log.error("The input's default value with id {} is not found", inputId);
3055 return Either.right(componentsUtils.getResponseFormat(
3056 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3060 * Method to delete selected nodes and edges on composition page
3061 * @param containerComponentType
3062 * @param componentId
3063 * @param componentInstanceIdList
3067 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3069 List<String> componentInstanceIdList,
3072 List<String> deleteErrorIds = new ArrayList<>();
3073 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3074 Either<Component, ResponseFormat> validateResponse = validateUser(containerComponentType, componentId, userId);
3075 if (validateResponse.isRight()) {
3076 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3077 return deleteErrorMap;
3079 Component containerComponent = validateResponse.left().value();
3081 Either<Boolean, ResponseFormat> lockComponent = lockComponent(
3082 containerComponent, "batchDeleteComponentInstance");
3083 if (lockComponent.isRight()) {
3084 log.error("Failed to lockComponent containerComponent");
3085 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3086 return deleteErrorMap;
3090 for (String eachInstanceId : componentInstanceIdList) {
3091 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3092 containerComponent, containerComponentType, componentId, eachInstanceId);
3093 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3094 if (actionResponse.isRight()) {
3095 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3096 deleteErrorIds.add(eachInstanceId);
3099 //sending the ids of the error nodes that were not deleted to UI
3100 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3101 return deleteErrorMap;
3103 unlockComponent(validateResponse, containerComponent);
3107 private Either<Component, ResponseFormat> validateUser(String containerComponentParam,
3108 String containerComponentId,
3110 validateUserExists(userId, "delete Component Instance", false);
3111 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
3112 if (validateComponentType.isRight()) {
3113 log.error("ComponentType[{}] doesn't support", containerComponentParam);
3114 return Either.right(validateComponentType.right().value());
3117 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
3118 Either<Component, ResponseFormat> validateComponentExists = validateComponentExists(
3119 containerComponentId, containerComponentType, null);
3120 if (validateComponentExists.isRight()) {
3121 log.error("Component Id[{}] doesn't exist", containerComponentId);
3122 return Either.right(validateComponentExists.right().value());
3125 Component containerComponent = validateComponentExists.left().value();
3126 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
3127 if (validateCanWorkOnComponent.isRight()) {
3128 return Either.right(validateCanWorkOnComponent.right().value());
3130 return Either.left(containerComponent);
3133 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3134 String containerComponentType,
3135 String containerComponentId,
3136 String componentInstanceId) {
3138 Either<ComponentInstance, ResponseFormat> resultOp;
3139 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3141 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3143 if (resultOp.isRight()) {
3144 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3145 return Either.right(resultOp.right().value());
3148 log.info("Successfully deleted instance with id {}", componentInstanceId);
3149 return Either.left(resultOp.left().value());