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.version.PostChangeVersionOperationOrchestrator;
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.CapabilityDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
41 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
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.ArtifactDefinition;
52 import org.openecomp.sdc.be.model.CapabilityDefinition;
53 import org.openecomp.sdc.be.model.Component;
54 import org.openecomp.sdc.be.model.ComponentInstance;
55 import org.openecomp.sdc.be.model.ComponentInstanceInput;
56 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
57 import org.openecomp.sdc.be.model.ComponentParametersView;
58 import org.openecomp.sdc.be.model.DataTypeDefinition;
59 import org.openecomp.sdc.be.model.GroupDefinition;
60 import org.openecomp.sdc.be.model.InputDefinition;
61 import org.openecomp.sdc.be.model.LifecycleStateEnum;
62 import org.openecomp.sdc.be.model.PropertyDefinition;
63 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
64 import org.openecomp.sdc.be.model.RelationshipInfo;
65 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
66 import org.openecomp.sdc.be.model.RequirementDefinition;
67 import org.openecomp.sdc.be.model.Resource;
68 import org.openecomp.sdc.be.model.Service;
69 import org.openecomp.sdc.be.model.User;
70 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
71 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
72 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
73 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
74 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
75 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
76 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
77 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
78 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
79 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
80 import org.openecomp.sdc.common.api.Constants;
81 import org.openecomp.sdc.common.datastructure.Wrapper;
82 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
83 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
84 import org.openecomp.sdc.common.util.ValidationUtils;
85 import org.openecomp.sdc.exception.ResponseFormat;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.springframework.beans.factory.annotation.Autowired;
90 import java.util.ArrayList;
91 import java.util.Collection;
92 import java.util.Collections;
93 import java.util.HashMap;
94 import java.util.Iterator;
95 import java.util.List;
97 import java.util.Map.Entry;
98 import java.util.Objects;
99 import java.util.Optional;
100 import java.util.Set;
101 import java.util.UUID;
102 import java.util.function.BiConsumer;
103 import java.util.stream.Collectors;
105 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
107 @org.springframework.stereotype.Component
108 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
110 private static final Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class);
113 private IComponentInstanceOperation componentInstanceOperation;
116 private ArtifactsBusinessLogic artifactBusinessLogic;
119 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
122 private PostChangeVersionOperationOrchestrator postChangeVersionOperationOrchestrator;
124 public static final String VF_MODULE = "org.openecomp.groups.VfModule";
126 public ComponentInstanceBusinessLogic() {
129 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
130 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
133 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
134 List<ComponentInstanceProperty> resList = new ArrayList<>();
135 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
136 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
137 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
139 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
141 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
143 ciName = ciOp.get().getName();
144 if (ciPropList != null && !ciPropList.isEmpty()) {
145 for(ComponentInstanceProperty prop: ciPropList){
146 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
147 if(inputsValues != null && !inputsValues.isEmpty()){
148 for(GetInputValueDataDefinition inputData: inputsValues){
149 if(isGetInputValueForInput(inputData, inputId)){
150 prop.setComponentInstanceId(s);
151 prop.setComponentInstanceName(ciName);
167 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
168 List<ComponentInstanceInput> resList = new ArrayList<>();
169 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
170 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
171 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
173 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
175 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
177 ciName = ciOp.get().getName();
178 if (ciPropList != null && !ciPropList.isEmpty()) {
179 for(ComponentInstanceInput prop: ciPropList){
180 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
181 if(inputsValues != null && !inputsValues.isEmpty()){
182 for(GetInputValueDataDefinition inputData: inputsValues){
183 if(isGetInputValueForInput(inputData, inputId)){
184 prop.setComponentInstanceId(s);
185 prop.setComponentInstanceName(ciName);
201 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
203 Component origComponent = null;
204 Either<ComponentInstance, ResponseFormat> resultOp = null;
206 org.openecomp.sdc.be.model.Component containerComponent = null;
207 ComponentTypeEnum containerComponentType;
210 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
211 if (resp.isRight()) {
212 return Either.right(resp.right().value());
214 user = resp.left().value();
217 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
218 if (validateValidJson.isRight()) {
219 return Either.right(validateValidJson.right().value());
222 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
223 if (validateComponentType.isRight()) {
224 return Either.right(validateComponentType.right().value());
226 containerComponentType = validateComponentType.left().value();
229 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
230 if (validateComponentExists.isRight()) {
231 return Either.right(validateComponentExists.right().value());
233 containerComponent = validateComponentExists.left().value();
236 if (ModelConverter.isAtomicComponent(containerComponent)) {
237 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
238 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
241 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
242 if (validateCanWorkOnComponent.isRight()) {
243 return Either.right(validateCanWorkOnComponent.right().value());
246 if (resourceInstance != null && containerComponentType != null) {
247 OriginTypeEnum originType = resourceInstance.getOriginType();
248 if (originType == OriginTypeEnum.ServiceProxy) {
249 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
250 if (serviceProxyOrigin.isRight()) {
251 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
252 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
254 origComponent = serviceProxyOrigin.left().value();
256 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
257 if (fillProxyRes != StorageOperationStatus.OK) {
258 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
259 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
264 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
266 if (getOriginComponentRes.isRight()) {
267 return Either.right(getOriginComponentRes.right().value());
269 origComponent = getOriginComponentRes.left().value();
274 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
275 if (lockComponent.isRight()) {
276 return Either.right(lockComponent.right().value());
279 log.debug("Try to create entry on graph");
280 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
285 unlockComponent(resultOp, containerComponent);
289 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
290 resourceInstance.setIsProxy(true);
291 ComponentParametersView filter = new ComponentParametersView(true);
292 filter.setIgnoreCapabilities(false);
293 filter.setIgnoreCapabiltyProperties(false);
294 filter.setIgnoreComponentInstances(false);
295 filter.setIgnoreRequirements(false);
296 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
297 if (serviceRes.isRight()) {
298 return serviceRes.right().value();
300 Component service = serviceRes.left().value();
301 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
302 resourceInstance.setCapabilities(capabilities);
303 Map<String, List<RequirementDefinition>> req = service.getRequirements();
304 resourceInstance.setRequirements(req);
306 String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
307 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
308 int lastIndexOf = toscaResourceName.lastIndexOf('.');
309 if (lastIndexOf != -1) {
310 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
311 resourceInstance.setToscaComponentName(proxyToscaName);
313 resourceInstance.setName(name);
314 resourceInstance.setIsProxy(true);
315 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
316 resourceInstance.setSourceModelName(service.getName());
317 resourceInstance.setSourceModelUuid(service.getUUID());
318 resourceInstance.setSourceModelUid(service.getUniqueId());
319 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
320 resourceInstance.setDescription("A Proxy for Service " + service.getName());
321 resourceInstance.setComponentVersion(service.getVersion());
323 return StorageOperationStatus.OK;
326 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
328 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
329 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
330 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
332 Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
333 if (resp.isRight()) {
334 return Either.right(resp.right().value());
337 User user = resp.left().value();
338 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
339 if (validateComponentType.isRight()) {
340 return Either.right(validateComponentType.right().value());
343 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
345 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
346 if (validateComponentExists.isRight()) {
347 return Either.right(validateComponentExists.right().value());
349 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
351 if (ModelConverter.isAtomicComponent(containerComponent)) {
352 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
353 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
356 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
357 if (validateCanWorkOnComponent.isRight()) {
358 return Either.right(validateCanWorkOnComponent.right().value());
361 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
362 if (lockComponent.isRight()) {
363 return Either.right(lockComponent.right().value());
367 log.debug("Try to create entry on graph");
368 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
370 if (eitherResourceName.isRight()) {
371 resultOp = Either.right(eitherResourceName.right().value());
374 Component origComponent = eitherResourceName.left().value();
376 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
377 if (result.isRight()) {
378 log.debug("Failed to create resource instance {}", containerComponentId);
379 resultOp = Either.right(result.right().value());
384 log.debug("Entity on graph is created.");
385 ComponentInstance resResourceInfo = result.left().value();
386 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
387 associationInfo.setFromNode(resResourceInfo.getUniqueId());
389 associationInfo.setToNode(resResourceInfo.getUniqueId());
392 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
393 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
394 if (resultReqCapDef.isLeft()) {
395 log.debug("Enty on graph is created.");
396 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
397 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
398 resultOp = Either.left(resInfo);
402 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
403 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
408 unlockComponent(resultOp, containerComponent);
412 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
413 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
416 private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
417 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
420 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
421 Either<Component, ResponseFormat> eitherResponse;
422 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
423 if (eitherComponent.isRight()) {
424 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
425 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
427 eitherResponse = Either.left(eitherComponent.left().value());
429 return eitherResponse;
432 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
433 Either<ComponentInstance, ResponseFormat> resultOp;
435 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
437 if (result.isRight()) {
438 log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
439 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
443 log.debug("Entity on graph is created.");
444 Component updatedComponent = result.left().value().getLeft();
445 Map<String, String> existingEnvVersions = new HashMap<>();
446 // TODO existingEnvVersions ??
447 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
448 if (addComponentInstanceArtifacts.isRight()) {
449 log.debug("Failed to create component instance {}", componentInstance.getName());
450 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
454 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
455 if (!updatedInstanceOptional.isPresent()) {
456 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
457 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
460 resultOp = Either.left(updatedInstanceOptional.get());
465 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
466 * @param containerComponent
467 * @param componentInstance
468 * @param originComponent
470 * @param existingEnvVersions
473 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) {
475 log.debug("add artifacts to resource instance");
476 List<GroupDefinition> filteredGroups = null;
477 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
478 if (!ActionStatus.OK.equals(status)) {
479 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
480 return Either.right(resultOp);
482 StorageOperationStatus artStatus;
483 // generate heat_env if necessary
484 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
485 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
487 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
488 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
490 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
491 String type = artifact.getArtifactType();
492 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
493 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
495 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
498 if (artifact.checkEsIdExist()) {
499 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
500 componentInstance.getName(), user, containerComponent, existingEnvVersions);
501 if (createHeatEnvPlaceHolder.isRight()) {
502 return Either.right(createHeatEnvPlaceHolder.right().value());
504 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
506 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
508 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
509 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
511 if (CollectionUtils.isNotEmpty(filteredGroups)) {
512 for (GroupDefinition groupInstance : filteredGroups) {
513 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
514 if (op.isPresent()) {
515 List<ArtifactDefinition> artifactsUid;
516 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
517 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
519 artifactsUid = new ArrayList<>();
521 artifactsUid.add(artifactDefinition);
522 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
529 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
530 if (artStatus != StorageOperationStatus.OK) {
531 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
532 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
535 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
536 if (result != StorageOperationStatus.OK) {
537 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
538 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
540 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
543 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
544 if (artStatus != StorageOperationStatus.OK) {
545 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
546 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
549 componentInstance.setArtifacts(originComponent.getArtifacts());
550 return Either.left(ActionStatus.OK);
553 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
554 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
556 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
557 if (getResourceDeploymentArtifacts.isRight()) {
558 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
559 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
560 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
561 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
564 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
567 if (!deploymentArtifacts.isEmpty()) {
568 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
569 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
570 if (!artifact.getValue().checkEsIdExist()) {
571 tempDeploymentArtifacts.remove(artifact.getKey());
575 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
578 return ActionStatus.OK;
581 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
582 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
585 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
586 boolean needLock, boolean createNewTransaction) {
588 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
589 if (resp.isRight()) {
590 return Either.right(resp.right().value());
593 Either<ComponentInstance, ResponseFormat> resultOp = null;
595 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
596 if (validateComponentType.isRight()) {
597 return Either.right(validateComponentType.right().value());
600 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
602 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
603 if (validateComponentExists.isRight()) {
604 return Either.right(validateComponentExists.right().value());
606 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
608 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
609 if (validateCanWorkOnComponent.isRight()) {
610 return Either.right(validateCanWorkOnComponent.right().value());
612 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
613 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
614 if (validateParentStatus.isRight()) {
615 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
616 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
619 if (!validateParentStatus.left().value()) {
620 resultOp = Either.right(
621 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
626 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
627 if (lockComponent.isRight()) {
628 return Either.right(lockComponent.right().value());
633 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
635 if (eitherResourceName.isRight()) {
636 resultOp = Either.right(eitherResourceName.right().value());
639 Component origComponent = eitherResourceName.left().value();
641 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
646 unlockComponent(resultOp, containerComponent);
650 // New Multiple Instance Update API
651 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
652 boolean createNewTransaction) {
654 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
655 org.openecomp.sdc.be.model.Component containerComponent = null;
657 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
658 if (resp.isRight()) {
659 return Either.right(resp.right().value());
662 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
663 if (validateComponentType.isRight()) {
664 return Either.right(validateComponentType.right().value());
667 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
669 ComponentParametersView componentFilter = new ComponentParametersView();
670 componentFilter.disableAll();
671 componentFilter.setIgnoreUsers(false);
672 componentFilter.setIgnoreComponentInstances(false);
673 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
674 if (validateComponentExists.isRight()) {
675 return Either.right(validateComponentExists.right().value());
678 containerComponent = validateComponentExists.left().value();
680 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
681 if (validateCanWorkOnComponent.isRight()) {
682 return Either.right(validateCanWorkOnComponent.right().value());
685 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
687 for (ComponentInstance componentInstance : componentInstanceList) {
688 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
689 if (!validateParent) {
690 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
691 containerComponentId));
698 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
699 if (lockComponent.isRight()) {
700 return Either.right(lockComponent.right().value());
704 List<ComponentInstance> updatedList = new ArrayList<>();
705 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
706 List<ComponentInstance> listForUpdate = new ArrayList<>();
707 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
708 containerComponent.setComponentInstances(componentInstanceList);
710 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
711 while (iterator.hasNext()) {
712 ComponentInstance origInst = iterator.next();
713 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
714 if (op.isPresent()) {
715 ComponentInstance updatedCi = op.get();
716 updatedCi = buildComponentInstance(updatedCi, origInst);
718 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
720 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());
721 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
725 listForUpdate.add(updatedCi);
727 listForUpdate.add(origInst);
729 containerComponent.setComponentInstances(listForUpdate);
731 if (resultOp == null) {
732 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
733 if (updateStatus.isRight()) {
734 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
735 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
738 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
739 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
740 if (op.isPresent()) {
741 updatedList.add(updatedInstance);
747 resultOp = Either.left(updatedList);
752 unlockComponent(resultOp, containerComponent);
757 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
758 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
761 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
762 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
763 return ComponentTypeEnum.SERVICE_INSTANCE;
765 return ComponentTypeEnum.RESOURCE_INSTANCE;
769 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
770 ComponentInstance componentInstance) {
772 Either<ComponentInstance, ResponseFormat> resultOp = null;
773 Optional<ComponentInstance> componentInstanceOptional = null;
774 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
775 ComponentInstance oldComponentInstance = null;
776 boolean isNameChanged = false;
778 if (resultOp == null) {
779 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
780 if (!componentInstanceOptional.isPresent()) {
781 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
782 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
785 if (resultOp == null) {
786 oldComponentInstance = componentInstanceOptional.get();
787 String newInstanceName = componentInstance.getName();
788 if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
789 isNameChanged = true;
790 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
792 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);
793 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
796 if (resultOp == null) {
797 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
798 if (updateRes.isRight()) {
799 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
800 updateRes.right().value());
801 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
803 // region - Update instance Groups
805 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
806 if (result.isRight())
807 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
812 if (resultOp == null) {
813 String newInstanceId = updateRes.left().value().getRight();
814 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
816 if (!updatedInstanceOptional.isPresent()) {
817 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
818 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
820 resultOp = Either.left(updatedInstanceOptional.get());
824 if (resultOp == null) {
825 resultOp = Either.left(componentInstanceOptional.get());
832 * The normalized old vf name
833 * @param newNormailzedPrefix-
834 * The normalized new vf name
835 * @param qualifiedGroupInstanceName-
836 * old Group Instance Name
838 // modify group names
839 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
840 if (qualifiedGroupInstanceName == null) {
841 log.info("CANNOT change group name ");
844 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
845 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
846 return qualifiedGroupInstanceName;
849 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
850 oldComponentInstance.setName(newComponentInstance.getName());
851 oldComponentInstance.setModificationTime(System.currentTimeMillis());
852 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
853 if (oldComponentInstance.getGroupInstances() != null)
854 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
855 return oldComponentInstance;
858 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
860 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
861 if (resp.isRight()) {
862 return Either.right(resp.right().value());
865 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
866 if (validateComponentType.isRight()) {
867 return Either.right(validateComponentType.right().value());
870 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
871 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
872 if (validateComponentExists.isRight()) {
873 return Either.right(validateComponentExists.right().value());
875 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
876 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
877 if (validateCanWorkOnComponent.isRight()) {
878 return Either.right(validateCanWorkOnComponent.right().value());
881 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
882 if (lockComponent.isRight()) {
883 return Either.right(lockComponent.right().value());
886 Either<ComponentInstance, ResponseFormat> resultOp = null;
888 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
889 if (resultOp.isRight()){
892 Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
893 containerComponentType, resultOp);
894 if (deleteEither.isRight()){
900 unlockComponent(resultOp, containerComponent);
904 public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
905 Either<ComponentInstance, ResponseFormat> resultOp) {
906 if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
907 final ComponentInstance componentInstance = resultOp.left().value();
908 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
909 if (!pathIDsToBeDeleted.isEmpty()) {
910 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
912 if(deleteForwardingPathsEither.isRight()) {
913 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
922 private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
924 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
925 if(storageStatus.isRight()) {
926 return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
928 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
929 Sets.newHashSet(pathIdsToDelete));
931 if(result.isRight()) {
932 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
934 return Either.left(result.left().value());
937 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
938 ComponentParametersView filter = new ComponentParametersView(true);
939 filter.setIgnoreForwardingPath(false);
940 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
941 .getToscaElement(containerComponentId, filter);
942 Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
943 List<String> pathIDsToBeDeleted = new ArrayList<>();
945 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
946 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
948 return pathIDsToBeDeleted;
951 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
952 String componentInstanceId){
953 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
954 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
955 elementDataDefinition.getToNode()
956 .equalsIgnoreCase(componentInstanceId));
960 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
962 Either<ComponentInstance, ResponseFormat> resultOp = null;
963 ComponentInstance deletedInstance = null;
964 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
966 if (deleteRes.isRight()) {
967 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
968 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
969 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
971 if (resultOp == null) {
972 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
973 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
974 resultOp = Either.left(deletedInstance);
976 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
977 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
978 for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
979 Map<String, String> members = currGroup.getMembers();
980 if (members != null && members.containsKey(deletedInstance.getName())) {
981 members.remove(deletedInstance.getName());
982 groupsToUpdate.add(currGroup);
985 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
986 if (updateGroupsRes.isRight()) {
987 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
988 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
989 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
992 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
993 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
994 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
995 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
996 if (deleteInputsRes != StorageOperationStatus.OK) {
997 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
998 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
1005 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1006 ComponentInstance foundInstance = null;
1007 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1008 if (instance.getUniqueId().equals(componentInstanceId)) {
1009 foundInstance = instance;
1010 containerComponent.getComponentInstances().remove(instance);
1014 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1015 return foundInstance;
1018 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1019 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1020 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1024 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1025 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1028 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1029 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1032 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1033 boolean createNewTransaction) {
1035 Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
1036 if (resp.isRight()) {
1037 return Either.right(resp.right().value());
1040 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1042 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1043 if (validateComponentExists.isRight()) {
1044 return Either.right(validateComponentExists.right().value());
1046 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1048 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1049 if (validateCanWorkOnComponent.isRight()) {
1050 return Either.right(validateCanWorkOnComponent.right().value());
1053 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1055 if (lockComponent.isRight()) {
1056 return Either.right(lockComponent.right().value());
1062 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1068 unlockComponent(resultOp, containerComponent);
1072 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1074 log.debug("Try to create entry on graph");
1075 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1077 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1079 if (result.isLeft()) {
1080 log.debug("Enty on graph is created.");
1081 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1082 resultOp = Either.left(requirementCapabilityRelDef);
1086 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1087 String fromNameOrId = "";
1088 String toNameOrId = "";
1089 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1090 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1092 toNameOrId = requirementDef.getFromNode();
1093 fromNameOrId = requirementDef.getFromNode();
1094 if (fromResult.isLeft()) {
1095 fromNameOrId = fromResult.left().value().getName();
1097 if (toResult.isLeft()) {
1098 toNameOrId = toResult.left().value().getName();
1101 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1108 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1109 Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
1110 if (resp.isRight()) {
1111 return Either.right(resp.right().value());
1114 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1115 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1116 if (validateComponentExists.isRight()) {
1117 return Either.right(validateComponentExists.right().value());
1119 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1121 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1122 if (validateCanWorkOnComponent.isRight()) {
1123 return Either.right(validateCanWorkOnComponent.right().value());
1125 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1127 if (lockComponent.isRight()) {
1128 return Either.right(lockComponent.right().value());
1131 log.debug("Try to create entry on graph");
1132 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1133 if (result.isLeft()) {
1134 log.debug("Enty on graph is created.");
1135 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1136 resultOp = Either.left(requirementCapabilityRelDef);
1141 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1142 String fromNameOrId = "";
1143 String toNameOrId = "";
1144 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1145 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1147 toNameOrId = requirementDef.getFromNode();
1148 fromNameOrId = requirementDef.getFromNode();
1149 if (fromResult.isLeft()) {
1150 fromNameOrId = fromResult.left().value().getName();
1152 if (toResult.isLeft()) {
1153 toNameOrId = toResult.left().value().getName();
1157 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1161 unlockComponent(resultOp, containerComponent);
1165 * Allows to get relation contained in specified component according to received Id
1166 * @param componentId
1169 * @param componentTypeEnum
1172 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1174 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1176 org.openecomp.sdc.be.model.Component containerComponent = null;
1177 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1178 RequirementCapabilityRelDef foundRelation = null;
1180 Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "get relation by Id", false);
1181 if (validateUserRes.isRight()) {
1182 resultOp = Either.right(validateUserRes.right().value());
1184 if(resultOp == null){
1185 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1186 if (validateComponentExists.isRight()) {
1187 resultOp = Either.right(validateComponentExists.right().value());
1190 if(resultOp == null){
1191 containerComponent = validateComponentExists.left().value();
1192 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1193 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1194 if(foundRelation == null){
1195 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1196 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1197 resultOp = Either.right(responseFormat);
1200 if(resultOp == null){
1201 resultOp = setRelatedCapability(foundRelation, containerComponent);
1203 if(resultOp.isLeft()){
1204 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1206 } catch (Exception e) {
1207 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1208 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1213 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1214 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1215 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1216 return relationship;
1222 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1223 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1224 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1225 String instanceId = foundRelation.getFromNode();
1226 Optional<RequirementDefinition> foundRequirement;
1227 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1228 if(!instance.isPresent()){
1229 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1230 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1231 result = Either.right(responseFormat);
1234 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1235 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1236 if(foundRequirement.isPresent()){
1237 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1238 result = Either.left(foundRelation);
1243 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1244 if(getfulfilledRequirementRes.isRight()){
1245 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1246 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1247 result = Either.right(responseFormat);
1249 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1253 result = Either.left(foundRelation);
1258 private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1259 return req.getName().equals(relationshipInfo.getRequirement()) &&
1260 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1261 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1264 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1265 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1266 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1267 String instanceId = foundRelation.getToNode();
1268 Optional<CapabilityDefinition> foundCapability;
1269 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1270 if(!instance.isPresent()){
1271 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1272 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1273 result = Either.right(responseFormat);
1276 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1277 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1278 if(foundCapability.isPresent()){
1279 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1280 result = Either.left(foundRelation);
1285 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1286 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1287 if(getfulfilledRequirementRes.isRight()){
1288 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1289 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1290 result = Either.right(responseFormat);
1292 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1296 result = Either.left(foundRelation);
1301 private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1302 return cap.getName().equals(relationshipInfo.getCapability()) &&
1303 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1304 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1307 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1308 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1309 Either<ComponentInstanceProperty, ResponseFormat> result;
1310 if (eitherAttribute.isLeft()) {
1311 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1312 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1314 result = Either.left(instanceAttribute);
1317 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1319 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1321 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1327 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1329 Either<ComponentInstanceProperty, ResponseFormat> result;
1331 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1332 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1333 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1335 if (!errorWrapper.isEmpty()) {
1336 result = Either.right(errorWrapper.getInnerElement());
1338 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1339 if (eitherAttribute.isLeft()) {
1340 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1341 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1342 result = Either.left(instanceAttribute);
1345 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1347 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1348 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1356 * Create Or Updates Attribute Instance
1358 * @param componentTypeEnum
1359 * @param componentId
1360 * @param resourceInstanceId
1365 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1366 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1367 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1369 validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
1370 if (errorWrapper.isEmpty()) {
1371 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1373 if (errorWrapper.isEmpty()) {
1374 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1376 if (errorWrapper.isEmpty()) {
1377 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1381 if (errorWrapper.isEmpty()) {
1382 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1384 result = createAttributeValue(attribute, resourceInstanceId);
1386 result = updateAttributeValue(attribute, resourceInstanceId);
1389 result = Either.right(errorWrapper.getInnerElement());
1395 if (result == null || result.isRight()) {
1396 titanDao.rollback();
1401 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1405 private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1406 return StringUtils.isNotEmpty(property.getValue())
1407 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1408 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1411 // US833308 VLI in service - specific network_role property value logic
1412 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1413 for (ComponentInstanceProperty property: properties) {
1414 if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1415 ComponentParametersView componentParametersView = new ComponentParametersView();
1416 componentParametersView.disableAll();
1417 componentParametersView.setIgnoreComponentInstances(false);
1418 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1419 if (getServiceResult.isRight()) {
1420 return getServiceResult.right().value();
1422 Component service = getServiceResult.left().value();
1423 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1424 if (!getInstance.isPresent()) {
1425 return StorageOperationStatus.NOT_FOUND;
1427 String prefix = service.getSystemName() + ".";
1428 String value = property.getValue();
1429 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1430 property.setValue(prefix + value);
1434 return StorageOperationStatus.OK;
1437 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1439 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1441 /*-------------------------------Validations---------------------------------*/
1443 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Properties Values", false);
1444 if (resp.isRight()) {
1445 return Either.right(resp.right().value());
1448 if (componentTypeEnum == null) {
1449 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO);
1450 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1453 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1455 if (getResourceResult.isRight()) {
1456 log.debug("Failed to retrieve component, component id {}", componentId);
1457 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1460 Component containerComponent = getResourceResult.left().value();
1462 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1463 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1464 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1467 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1468 if (resourceInstanceStatus.isRight()) {
1469 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1472 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1473 // specific property value logic US833308
1474 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1475 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1476 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1480 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1481 if (lockStatus != StorageOperationStatus.OK) {
1482 log.debug("Failed to lock service {}", componentId);
1483 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1488 for (ComponentInstanceProperty property: properties) {
1489 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1490 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1491 responseFormat -> Either.right(responseFormat));
1494 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1495 if (updateContainerRes.isRight()) {
1496 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1497 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1500 resultOp = Either.left(properties);
1504 if (resultOp == null || resultOp.isRight()) {
1505 titanDao.rollback();
1510 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1514 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1515 String capabilityType, String capabilityName) {
1516 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1517 StringBuffer sb = new StringBuffer(componentInstanceUniqueId);
1518 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1519 String capKey = sb.toString();
1521 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1522 .orElse(Collections.emptyMap());
1523 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1524 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1525 if (cap.isPresent()) {
1526 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1527 if (capProperties != null) {
1528 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1529 StorageOperationStatus status;
1530 if (instanceProperty.isPresent()) {
1531 instanceProperty.get().setValue(newValue);
1532 List<String> path = new ArrayList<>();
1533 path.add(componentInstanceUniqueId);
1535 instanceProperty.get().setPath(path);
1536 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1537 if (status != StorageOperationStatus.OK) {
1538 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1539 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1542 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1548 return componentsUtils.getResponseFormat(ActionStatus.OK);
1551 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1552 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1553 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1554 StorageOperationStatus status;
1555 instanceProperty.get().setValue(newValue);
1556 if (instanceProperty.isPresent()) {
1557 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1559 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1561 if (status != StorageOperationStatus.OK) {
1562 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1563 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1565 List<String> path = new ArrayList<>();
1566 path.add(foundResourceInstance.getUniqueId());
1567 property.setPath(path);
1569 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1570 return componentsUtils.getResponseFormat(ActionStatus.OK);
1573 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1574 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1575 if (allDataTypesEither.isRight()) {
1576 TitanOperationStatus status = allDataTypesEither.right().value();
1577 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1578 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1580 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1581 String innerType = null;
1582 String propertyType = property.getType();
1583 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1584 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1586 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1587 SchemaDefinition def = property.getSchema();
1589 log.debug("Schema doesn't exists for property of type {}", type);
1590 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1592 PropertyDataDefinition propDef = def.getProperty();
1593 if (propDef == null) {
1594 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1595 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1597 innerType = propDef.getType();
1599 // Specific Update Logic
1600 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1601 String newValue = property.getValue();
1602 if (isValid.isRight()) {
1603 Boolean res = isValid.right().value();
1605 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1608 Object object = isValid.left().value();
1609 if (object != null) {
1610 newValue = object.toString();
1614 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1615 if (pair.getRight() != null && pair.getRight() == false) {
1616 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1617 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1620 return Either.left(newValue);
1623 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1624 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1625 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1626 StorageOperationStatus status;
1627 if (instanceProperty.isPresent()) {
1628 instanceProperty.get().setValue(input.getValue());
1629 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1631 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1633 if (status != StorageOperationStatus.OK) {
1634 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1635 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1637 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1638 return componentsUtils.getResponseFormat(ActionStatus.OK);
1641 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1643 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1645 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1646 if (resp.isRight()) {
1647 return Either.right(resp.right().value());
1650 if (componentTypeEnum == null) {
1651 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1652 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1655 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1657 if (getResourceResult.isRight()) {
1658 log.debug("Failed to retrieve component, component id {}", componentId);
1659 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1662 Component containerComponent = getResourceResult.left().value();
1664 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1665 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1666 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1669 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1670 if (resourceInstanceStatus.isRight()) {
1671 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1675 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1678 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1679 if (lockStatus != StorageOperationStatus.OK) {
1680 log.debug("Failed to lock service {}", componentId);
1681 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1685 for (ComponentInstanceInput input: inputs) {
1686 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1687 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1688 responseFormat -> Either.right(responseFormat));
1691 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1693 if (updateContainerRes.isRight()) {
1694 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1695 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1698 resultOp = Either.left(inputs);
1702 if (resultOp == null || resultOp.isRight()) {
1703 titanDao.rollback();
1708 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1713 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1716 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1718 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1719 if (resp.isRight()) {
1720 return Either.right(resp.right().value());
1723 if (componentTypeEnum == null) {
1724 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1725 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1729 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1730 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1731 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1735 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1736 if (lockStatus != StorageOperationStatus.OK) {
1737 log.debug("Failed to lock service {}", componentId);
1738 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1742 String propertyValueUid = property.getValueUniqueUid();
1744 if (propertyValueUid == null) {
1746 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1748 if (counterRes.isRight()) {
1749 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1750 StorageOperationStatus status = counterRes.right().value();
1751 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1752 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1754 Integer index = counterRes.left().value();
1755 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1757 if (result.isLeft()) {
1758 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1759 ComponentInstanceProperty instanceProperty = result.left().value();
1761 resultOp = Either.left(instanceProperty);
1764 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1766 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1768 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1772 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1774 if (result.isLeft()) {
1775 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1776 ComponentInstanceProperty instanceProperty = result.left().value();
1778 resultOp = Either.left(instanceProperty);
1781 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1783 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1785 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1788 if (resultOp.isLeft()) {
1789 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1790 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1791 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1793 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1800 if (resultOp == null || resultOp.isRight()) {
1801 titanDao.rollback();
1806 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1811 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1813 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1815 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
1816 if (resp.isRight()) {
1817 return Either.right(resp.right().value());
1820 if (componentTypeEnum == null) {
1821 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1822 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1826 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1827 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1828 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1832 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1833 if (lockStatus != StorageOperationStatus.OK) {
1834 log.debug("Failed to lock service {}", componentId);
1835 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1839 String propertyValueUid = inputProperty.getValueUniqueUid();
1840 if (propertyValueUid == null) {
1842 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1844 if (counterRes.isRight()) {
1845 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1846 StorageOperationStatus status = counterRes.right().value();
1847 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1848 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1850 Integer index = counterRes.left().value();
1851 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1853 if (result.isLeft()) {
1854 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1855 ComponentInstanceInput instanceProperty = result.left().value();
1857 resultOp = Either.left(instanceProperty);
1861 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1863 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1865 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1871 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1873 if (result.isLeft()) {
1874 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1875 ComponentInstanceInput instanceProperty = result.left().value();
1877 resultOp = Either.left(instanceProperty);
1881 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1883 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1885 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1892 if (resultOp == null || resultOp.isRight()) {
1893 titanDao.rollback();
1898 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1903 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1905 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
1906 if (resp.isRight()) {
1907 return Either.right(resp.right().value());
1910 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1912 if (componentTypeEnum == null) {
1913 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1914 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1918 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1919 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1920 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1924 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1925 if (lockStatus != StorageOperationStatus.OK) {
1926 log.debug("Failed to lock service {}", serviceId);
1927 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1931 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1933 if (result.isLeft()) {
1934 log.debug("Property value {} was removed from graph.", propertyValueId);
1935 ComponentInstanceProperty instanceProperty = result.left().value();
1937 resultOp = Either.left(instanceProperty);
1941 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1943 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1945 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1951 if (resultOp == null || resultOp.isRight()) {
1952 titanDao.rollback();
1957 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1962 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1964 Either<Component, ResponseFormat> eitherResponse = null;
1965 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1966 Component component;
1967 ResponseFormat errorResponse;
1968 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1969 if (getComponentRes.isRight()) {
1970 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1971 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1972 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1973 eitherResponse = Either.right(errorResponse);
1975 if (eitherResponse == null) {
1976 component = getComponentRes.left().value();
1977 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1978 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1979 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1980 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1981 eitherResponse = Either.right(errorResponse);
1984 if (eitherResponse == null) {
1985 eitherResponse = Either.left(getComponentRes.left().value());
1987 return eitherResponse;
1990 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
1991 String containerComponentId,
1992 String componentInstanceId,
1993 ComponentInstance newComponentInstance) {
1994 Either<Set<String>, ResponseFormat> resultOp;
1995 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1996 if (validateComponentType.isRight()) {
1997 return Either.right(validateComponentType.right().value());
1999 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2000 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2003 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
2004 validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2005 if (validateComponentExists.isRight()) {
2006 return Either.right(validateComponentExists.right().value());
2008 Component containerComponent = validateComponentExists.left().value();
2010 //Fetch current component instance
2011 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2012 getResourceInstanceById(containerComponent, componentInstanceId);
2013 if (eitherResourceInstance.isRight()) {
2014 resultOp = Either.right(componentsUtils.getResponseFormat(
2015 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2018 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2020 //Check whether new componentInstance exists
2021 String resourceId = newComponentInstance.getComponentUid();
2022 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2023 if (componentExistsRes.isRight()) {
2024 log.debug("Failed to find resource ", resourceId);
2025 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2026 (componentExistsRes.right().value()), resourceId));
2028 } else if (!componentExistsRes.left().value()) {
2029 log.debug("The resource {} not found ", resourceId);
2030 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2034 //Fetch component using new component instance uid
2035 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2036 if (eitherResourceName.isRight()) {
2037 resultOp = Either.right(eitherResourceName.right().value());
2040 Component updatedContainerComponent=eitherResourceName.left().value();
2041 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2042 currentResourceInstance, updatedContainerComponent);
2043 resultOp=Either.left(toDeleteForwardingPaths);
2048 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2049 Component updatedContainerComponent) {
2050 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2051 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2053 Service service = (Service) containerComponent;
2054 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2056 return forwardingPathUtils.
2057 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2060 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2061 ComponentParametersView componentParametersView = new ComponentParametersView();
2062 componentParametersView.setIgnoreCapabiltyProperties(false);
2063 componentParametersView.setIgnoreForwardingPath(false);
2064 return componentParametersView;
2067 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2069 Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
2070 if (resp.isRight()) {
2071 return Either.right(resp.right().value());
2074 User user = resp.left().value();
2075 Either<ComponentInstance, ResponseFormat> resultOp = null;
2077 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2078 if (validateComponentType.isRight()) {
2079 return Either.right(validateComponentType.right().value());
2082 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2083 ComponentParametersView componentParametersView = new ComponentParametersView();
2084 componentParametersView.setIgnoreCapabiltyProperties(false);
2085 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2086 if (validateComponentExists.isRight()) {
2087 return Either.right(validateComponentExists.right().value());
2089 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2091 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2092 if (validateCanWorkOnComponent.isRight()) {
2093 return Either.right(validateCanWorkOnComponent.right().value());
2096 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2097 if (resourceInstanceStatus.isRight()) {
2098 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2102 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2104 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2105 if (lockComponent.isRight()) {
2106 return Either.right(lockComponent.right().value());
2112 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2113 resultOp = Either.left(currentResourceInstance);
2117 String resourceId = newComponentInstance.getComponentUid();
2121 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2122 if (componentExistsRes.isRight()) {
2123 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2124 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2126 } else if (!componentExistsRes.left().value()) {
2127 log.debug("The resource {} not found ", resourceId);
2128 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2132 Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2134 if (eitherOriginComponent.isRight()) {
2135 resultOp = Either.right(eitherOriginComponent.right().value());
2138 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2139 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2140 if (resultOp.isRight()) {
2141 log.debug("failed to delete resource instance {}", resourceId);
2144 ComponentInstance resResourceInfo = resultOp.left().value();
2145 Component origComponent = null;
2146 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2147 if (originType == OriginTypeEnum.ServiceProxy) {
2148 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2149 if (serviceProxyOrigin.isRight()) {
2150 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2151 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2153 origComponent = serviceProxyOrigin.left().value();
2155 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2157 if (fillProxyRes != StorageOperationStatus.OK) {
2158 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2159 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2162 newComponentInstance.setOriginType(originType);
2166 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2168 if (eitherResourceName.isRight()) {
2169 resultOp = Either.right(eitherResourceName.right().value());
2173 origComponent = eitherResourceName.left().value();
2175 newComponentInstance.setName(resResourceInfo.getName());
2178 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2179 newComponentInstance.setPosX(resResourceInfo.getPosX());
2180 newComponentInstance.setPosY(resResourceInfo.getPosY());
2181 newComponentInstance.setDescription(resResourceInfo.getDescription());
2183 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2185 if (resultOp.isRight()) {
2186 log.debug("failed to create resource instance {}", resourceId);
2190 ComponentInstance updatedComponentInstance = resultOp.left().value();
2191 if (resultOp.isRight()) {
2192 log.debug("failed to create resource instance {}", resourceId);
2196 Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2197 if (mergeStatusEither.isRight()) {
2198 return Either.right(mergeStatusEither.right().value());
2201 ActionStatus postChangeVersionResult = postChangeVersionOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2202 if (postChangeVersionResult != ActionStatus.OK) {
2203 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2206 ComponentParametersView filter = new ComponentParametersView(true);
2207 filter.setIgnoreComponentInstances(false);
2208 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2209 if (updatedComponentRes.isRight()) {
2210 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2211 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2212 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2213 log.debug("Component with id {} was not found", containerComponentId);
2214 return Either.right(responseFormat);
2216 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2217 if (resourceInstanceStatus.isRight()) {
2218 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2221 resultOp = Either.left(resourceInstanceStatus.left().value());
2225 unlockComponent(resultOp, containerComponent);
2230 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2231 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2232 Component containerComponent = null;
2234 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2236 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2237 if (validateUserExists.isRight()) {
2238 resultOp = Either.right(validateUserExists.right().value());
2242 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2243 if (validateComponentType.isRight()) {
2244 resultOp = Either.right(validateComponentType.right().value());
2248 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2249 if (validateContainerComponentExists.isRight()) {
2250 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2253 containerComponent = validateContainerComponentExists.left().value();
2255 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2256 if (resourceInstanceStatus.isRight()) {
2257 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2261 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2262 if (CollectionUtils.isEmpty(instanceProperties)) {
2263 instanceProperties = new ArrayList<>();
2265 resultOp = Either.left(instanceProperties);
2268 unlockComponent(resultOp, containerComponent);
2272 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2273 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2275 if (counterRes.isRight()) {
2276 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2277 StorageOperationStatus status = counterRes.right().value();
2278 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2279 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2281 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2287 * updates componentInstance modificationTime
2289 * @param componentInstance
2290 * @param componentInstanceType
2291 * @param modificationTime
2292 * @param inTransaction
2295 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2296 Either<ComponentInstanceData, ResponseFormat> result;
2297 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2299 if (updateComponentInstanceRes.isRight()) {
2300 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2301 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2303 result = Either.left(updateComponentInstanceRes.left().value());
2308 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
2309 // TODO Add implementation
2310 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2314 public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
2315 // TODO Add implementation
2316 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2320 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
2321 // TODO Add implementation
2322 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2326 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2327 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2330 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2332 Either<ComponentInstance, StorageOperationStatus> result = null;
2333 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2334 Optional<ComponentInstance> foundInstance = null;
2335 if (CollectionUtils.isEmpty(instances)) {
2336 result = Either.right(StorageOperationStatus.NOT_FOUND);
2338 if (result == null) {
2339 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2340 if (!foundInstance.isPresent()) {
2341 result = Either.right(StorageOperationStatus.NOT_FOUND);
2344 if (result == null) {
2345 result = Either.left(foundInstance.get());
2350 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2352 Long creationDate = origInstanceForUpdate.getCreationTime();
2354 Long modificationTime = System.currentTimeMillis();
2355 resourceInstanceForUpdate.setCreationTime(creationDate);
2356 resourceInstanceForUpdate.setModificationTime(modificationTime);
2358 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2360 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2361 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2364 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2366 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2367 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2369 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2370 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2372 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2373 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2375 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2376 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2378 if (resourceInstanceForUpdate.getOriginType() == null) {
2379 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2381 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2382 resourceInstanceForUpdate.setIsProxy(true);
2383 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2384 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2386 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2387 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2389 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2390 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2392 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2393 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2395 return resourceInstanceForUpdate;
2398 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2399 * @param containerComponentType
2400 * @param containerComponentId
2401 * @param componentInstanceUniqueId
2402 * @param capabilityType
2403 * @param capabilityName
2408 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2410 Component containerComponent = null;
2412 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2414 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false);
2415 if (validateUserExists.isRight()) {
2416 resultOp = Either.right(validateUserExists.right().value());
2418 if(resultOp == null){
2419 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2420 if (validateComponentType.isRight()) {
2421 resultOp = Either.right(validateComponentType.right().value());
2424 if(resultOp == null){
2425 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2426 if (validateContainerComponentExists.isRight()) {
2427 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2429 containerComponent = validateContainerComponentExists.left().value();
2432 if(resultOp == null){
2433 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2434 if (resourceInstanceStatus.isRight()) {
2435 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2437 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2442 unlockComponent(resultOp, containerComponent);
2446 private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2447 Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2448 CapabilityDefinition foundCapability;
2449 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2450 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2451 if (capabilitiesPerType != null) {
2452 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2453 if (capabilityOpt.isPresent()) {
2454 foundCapability = capabilityOpt.get();
2455 result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2459 if (result == null) {
2460 result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2465 private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2466 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2468 Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2469 if(getComponentInstanceCapabilityProperties.isRight()){
2470 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2472 resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
2474 } catch(Exception e){
2475 log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2476 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2481 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2482 String capabilityType, String capabilityName, String ownerId) {
2483 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2484 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2485 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2486 String capKey = sb.toString();
2488 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2489 .orElse(Collections.emptyMap());
2490 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2491 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2492 if (cap.isPresent()) {
2493 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2494 if (capProperties != null) {
2495 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2496 StorageOperationStatus status;
2497 if (instanceProperty.isPresent()) {
2498 instanceProperty.get().setValue(newValue);
2499 List<String> path = new ArrayList<>();
2500 path.add(componentInstanceUniqueId);
2502 instanceProperty.get().setPath(path);
2503 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2504 if (status != StorageOperationStatus.OK) {
2505 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2506 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2509 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2513 return componentsUtils.getResponseFormat(ActionStatus.OK);
2516 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2517 List<ComponentInstanceProperty> properties, String userId) {
2518 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2520 Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
2521 if (resp.isRight()) {
2522 return Either.right(resp.right().value());
2525 if (componentTypeEnum == null) {
2526 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2527 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2529 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2531 if (getResourceResult.isRight()) {
2532 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2533 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2535 Component containerComponent = getResourceResult.left().value();
2537 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2538 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2539 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2541 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2542 if (resourceInstanceStatus.isRight()) {
2543 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2545 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2547 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2548 if (lockStatus != StorageOperationStatus.OK) {
2549 log.debug("Failed to lock component {}", containerComponentId);
2550 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2553 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2554 if (allDataTypes.isRight()) {
2555 TitanOperationStatus status = allDataTypes.right().value();
2556 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2557 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2561 for (ComponentInstanceProperty property : properties) {
2562 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2563 newPropertyValueEither.bimap(updatedValue ->
2564 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2565 responseFormat -> Either.right(responseFormat));
2567 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2569 if (updateContainerRes.isRight()) {
2570 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2571 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2574 resultOp = Either.left(properties);
2578 if (resultOp == null || resultOp.isRight()) {
2579 titanDao.rollback();
2584 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2588 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2589 List<ComponentInstanceProperty> properties, String userId) {
2590 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2592 Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
2593 if (resp.isRight()) {
2594 return Either.right(resp.right().value());
2597 if (componentTypeEnum == null) {
2598 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2599 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2601 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2603 if (getResourceResult.isRight()) {
2604 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2605 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2607 Component containerComponent = getResourceResult.left().value();
2609 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2610 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2611 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2613 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2614 if (resourceInstanceStatus.isRight()) {
2615 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2617 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2619 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2620 if (lockStatus != StorageOperationStatus.OK) {
2621 log.debug("Failed to lock component {}", containerComponentId);
2622 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2626 for (ComponentInstanceProperty property : properties) {
2627 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2628 newPropertyValueEither.bimap(updatedValue ->
2629 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2630 responseFormat -> Either.right(responseFormat));
2632 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2634 if (updateContainerRes.isRight()) {
2635 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2636 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2639 resultOp = Either.left(properties);
2643 if (resultOp == null || resultOp.isRight()) {
2644 titanDao.rollback();
2649 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());