2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.collect.Sets;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
30 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
31 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
32 import org.openecomp.sdc.be.components.validation.ComponentValidations;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
37 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
38 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
39 import org.openecomp.sdc.be.datatypes.elements.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.ForwardingPathOperation;
71 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
72 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
73 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
74 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
75 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
76 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
77 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
78 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
79 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
80 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
81 import org.openecomp.sdc.common.api.Constants;
82 import org.openecomp.sdc.common.datastructure.Wrapper;
83 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
84 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
85 import org.openecomp.sdc.common.log.wrappers.Logger;
86 import org.openecomp.sdc.common.util.ValidationUtils;
87 import org.openecomp.sdc.exception.ResponseFormat;
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 = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
111 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
112 public static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
113 public static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
114 public static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
115 public static final String INVALID_COMPONENT_TYPE = "invalid component type";
116 public static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
117 public static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
118 public static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
121 private IComponentInstanceOperation componentInstanceOperation;
124 private ArtifactsBusinessLogic artifactBusinessLogic;
127 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
130 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
133 private ForwardingPathOperation forwardingPathOperation;
136 public ComponentInstanceBusinessLogic() {
139 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
140 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
143 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
144 List<ComponentInstanceProperty> resList = new ArrayList<>();
145 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
146 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
147 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
149 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
151 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
153 ciName = ciOp.get().getName();
154 if (ciPropList != null && !ciPropList.isEmpty()) {
155 for(ComponentInstanceProperty prop: ciPropList){
156 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
157 if(inputsValues != null && !inputsValues.isEmpty()){
158 for(GetInputValueDataDefinition inputData: inputsValues){
159 if(isGetInputValueForInput(inputData, inputId)){
160 prop.setComponentInstanceId(s);
161 prop.setComponentInstanceName(ciName);
177 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
178 List<ComponentInstanceInput> resList = new ArrayList<>();
179 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
180 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
181 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
183 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
185 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
187 ciName = ciOp.get().getName();
188 if (ciPropList != null && !ciPropList.isEmpty()) {
189 for(ComponentInstanceInput prop: ciPropList){
190 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
191 if(inputsValues != null && !inputsValues.isEmpty()){
192 for(GetInputValueDataDefinition inputData: inputsValues){
193 if(isGetInputValueForInput(inputData, inputId)){
194 prop.setComponentInstanceId(s);
195 prop.setComponentInstanceName(ciName);
211 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
213 Component origComponent = null;
214 Either<ComponentInstance, ResponseFormat> resultOp = null;
216 org.openecomp.sdc.be.model.Component containerComponent = null;
217 ComponentTypeEnum containerComponentType;
220 user = validateUserExists(userId, "create Component Instance", inTransaction);
222 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
223 if (validateValidJson.isRight()) {
224 return Either.right(validateValidJson.right().value());
227 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
228 if (validateComponentType.isRight()) {
229 return Either.right(validateComponentType.right().value());
231 containerComponentType = validateComponentType.left().value();
234 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
235 if (validateComponentExists.isRight()) {
236 return Either.right(validateComponentExists.right().value());
238 containerComponent = validateComponentExists.left().value();
241 if (ModelConverter.isAtomicComponent(containerComponent)) {
242 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
243 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
246 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
247 if (validateCanWorkOnComponent.isRight()) {
248 return Either.right(validateCanWorkOnComponent.right().value());
251 if (resourceInstance != null && containerComponentType != null) {
252 OriginTypeEnum originType = resourceInstance.getOriginType();
253 if (originType == OriginTypeEnum.ServiceProxy) {
254 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
255 if (serviceProxyOrigin.isRight()) {
256 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
257 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
259 origComponent = serviceProxyOrigin.left().value();
261 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
262 if (fillProxyRes != StorageOperationStatus.OK) {
263 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
264 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
269 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
271 if (getOriginComponentRes.isRight()) {
272 return Either.right(getOriginComponentRes.right().value());
274 origComponent = getOriginComponentRes.left().value();
279 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
280 if (lockComponent.isRight()) {
281 return Either.right(lockComponent.right().value());
284 log.debug("Try to create entry on graph");
285 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
290 unlockComponent(resultOp, containerComponent);
294 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
295 resourceInstance.setIsProxy(true);
296 ComponentParametersView filter = new ComponentParametersView(true);
297 filter.setIgnoreCapabilities(false);
298 filter.setIgnoreCapabiltyProperties(false);
299 filter.setIgnoreComponentInstances(false);
300 filter.setIgnoreRequirements(false);
301 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
302 if (serviceRes.isRight()) {
303 return serviceRes.right().value();
305 Component service = serviceRes.left().value();
306 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
307 resourceInstance.setCapabilities(capabilities);
308 Map<String, List<RequirementDefinition>> req = service.getRequirements();
309 resourceInstance.setRequirements(req);
311 String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
312 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
313 int lastIndexOf = toscaResourceName.lastIndexOf('.');
314 if (lastIndexOf != -1) {
315 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
316 resourceInstance.setToscaComponentName(proxyToscaName);
318 resourceInstance.setName(name);
319 resourceInstance.setIsProxy(true);
320 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
321 resourceInstance.setSourceModelName(service.getName());
322 resourceInstance.setSourceModelUuid(service.getUUID());
323 resourceInstance.setSourceModelUid(service.getUniqueId());
324 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
325 resourceInstance.setDescription("A Proxy for Service " + service.getName());
326 resourceInstance.setComponentVersion(service.getVersion());
328 return StorageOperationStatus.OK;
331 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
333 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
334 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
335 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
337 User user = validateUserExists(userId, "create And Associate RI To RI", false);
339 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
340 if (validateComponentType.isRight()) {
341 return Either.right(validateComponentType.right().value());
344 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
346 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
347 if (validateComponentExists.isRight()) {
348 return Either.right(validateComponentExists.right().value());
350 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
352 if (ModelConverter.isAtomicComponent(containerComponent)) {
353 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
354 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
357 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
358 if (validateCanWorkOnComponent.isRight()) {
359 return Either.right(validateCanWorkOnComponent.right().value());
362 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
363 if (lockComponent.isRight()) {
364 return Either.right(lockComponent.right().value());
368 log.debug("Try to create entry on graph");
369 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
371 if (eitherResourceName.isRight()) {
372 resultOp = Either.right(eitherResourceName.right().value());
375 Component origComponent = eitherResourceName.left().value();
377 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
378 if (result.isRight()) {
379 log.debug("Failed to create resource instance {}", containerComponentId);
380 resultOp = Either.right(result.right().value());
385 log.debug("Entity on graph is created.");
386 ComponentInstance resResourceInfo = result.left().value();
387 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
388 associationInfo.setFromNode(resResourceInfo.getUniqueId());
390 associationInfo.setToNode(resResourceInfo.getUniqueId());
393 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
394 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
395 if (resultReqCapDef.isLeft()) {
396 log.debug("Enty on graph is created.");
397 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
398 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
399 resultOp = Either.left(resInfo);
403 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
404 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
409 unlockComponent(resultOp, containerComponent);
413 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
414 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
417 private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
418 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
421 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
422 Either<Component, ResponseFormat> eitherResponse;
423 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
424 if (eitherComponent.isRight()) {
425 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
426 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
428 eitherResponse = Either.left(eitherComponent.left().value());
430 return eitherResponse;
433 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
434 Either<ComponentInstance, ResponseFormat> resultOp;
436 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
438 if (result.isRight()) {
439 log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
440 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
444 log.debug("Entity on graph is created.");
445 Component updatedComponent = result.left().value().getLeft();
446 Map<String, String> existingEnvVersions = new HashMap<>();
447 // TODO existingEnvVersions ??
448 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
449 if (addComponentInstanceArtifacts.isRight()) {
450 log.debug("Failed to create component instance {}", componentInstance.getName());
451 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
455 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
456 if (!updatedInstanceOptional.isPresent()) {
457 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
458 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
461 resultOp = Either.left(updatedInstanceOptional.get());
466 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
467 * @param containerComponent
468 * @param componentInstance
469 * @param originComponent
471 * @param existingEnvVersions
474 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) {
476 log.debug("add artifacts to resource instance");
477 List<GroupDefinition> filteredGroups = null;
478 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
479 if (!ActionStatus.OK.equals(status)) {
480 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
481 return Either.right(resultOp);
483 StorageOperationStatus artStatus;
484 // generate heat_env if necessary
485 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
486 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
488 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
489 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
491 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
492 String type = artifact.getArtifactType();
493 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
494 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
496 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
499 if (artifact.checkEsIdExist()) {
500 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
501 componentInstance.getName(), user, containerComponent, existingEnvVersions);
502 if (createHeatEnvPlaceHolder.isRight()) {
503 return Either.right(createHeatEnvPlaceHolder.right().value());
505 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
507 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
509 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
510 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
512 if (CollectionUtils.isNotEmpty(filteredGroups)) {
513 for (GroupDefinition groupInstance : filteredGroups) {
514 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
515 if (op.isPresent()) {
516 List<ArtifactDefinition> artifactsUid;
517 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
518 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
520 artifactsUid = new ArrayList<>();
522 artifactsUid.add(artifactDefinition);
523 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
530 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
531 if (artStatus != StorageOperationStatus.OK) {
532 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
533 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
536 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
537 if (result != StorageOperationStatus.OK) {
538 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
539 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
541 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
544 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
545 if (artStatus != StorageOperationStatus.OK) {
546 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
547 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
550 componentInstance.setArtifacts(originComponent.getArtifacts());
551 return Either.left(ActionStatus.OK);
554 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
555 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
557 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
558 if (getResourceDeploymentArtifacts.isRight()) {
559 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
560 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
561 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
562 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
565 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
568 if (!deploymentArtifacts.isEmpty()) {
569 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
570 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
571 if (!artifact.getValue().checkEsIdExist()) {
572 tempDeploymentArtifacts.remove(artifact.getKey());
576 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
579 return ActionStatus.OK;
582 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
583 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
586 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
587 boolean needLock, boolean createNewTransaction) {
589 validateUserExists(userId, "update Component Instance", inTransaction);
591 Either<ComponentInstance, ResponseFormat> resultOp = null;
593 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
594 if (validateComponentType.isRight()) {
595 return Either.right(validateComponentType.right().value());
598 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
600 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
601 if (validateComponentExists.isRight()) {
602 return Either.right(validateComponentExists.right().value());
604 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
606 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
607 if (validateCanWorkOnComponent.isRight()) {
608 return Either.right(validateCanWorkOnComponent.right().value());
610 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
611 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
612 if (validateParentStatus.isRight()) {
613 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
614 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
617 if (!validateParentStatus.left().value()) {
618 resultOp = Either.right(
619 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
624 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
625 if (lockComponent.isRight()) {
626 return Either.right(lockComponent.right().value());
631 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
633 if (eitherResourceName.isRight()) {
634 resultOp = Either.right(eitherResourceName.right().value());
637 Component origComponent = eitherResourceName.left().value();
639 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
644 unlockComponent(resultOp, containerComponent);
648 // New Multiple Instance Update API
649 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
651 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
652 org.openecomp.sdc.be.model.Component containerComponent = null;
654 validateUserExists(userId, "update Component Instance", true);
656 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
657 if (validateComponentType.isRight()) {
658 return Either.right(validateComponentType.right().value());
661 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
663 ComponentParametersView componentFilter = new ComponentParametersView();
664 componentFilter.disableAll();
665 componentFilter.setIgnoreUsers(false);
666 componentFilter.setIgnoreComponentInstances(false);
667 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
668 if (validateComponentExists.isRight()) {
669 return Either.right(validateComponentExists.right().value());
672 containerComponent = validateComponentExists.left().value();
674 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
675 if (validateCanWorkOnComponent.isRight()) {
676 return Either.right(validateCanWorkOnComponent.right().value());
679 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
681 for (ComponentInstance componentInstance : componentInstanceList) {
682 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
683 if (!validateParent) {
684 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
685 containerComponentId));
692 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
693 if (lockComponent.isRight()) {
694 return Either.right(lockComponent.right().value());
698 List<ComponentInstance> updatedList = new ArrayList<>();
699 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
700 List<ComponentInstance> listForUpdate = new ArrayList<>();
701 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
702 containerComponent.setComponentInstances(componentInstanceList);
704 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
705 while (iterator.hasNext()) {
706 ComponentInstance origInst = iterator.next();
707 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
708 if (op.isPresent()) {
709 ComponentInstance updatedCi = op.get();
710 updatedCi = buildComponentInstance(updatedCi, origInst);
712 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
714 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());
715 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
719 listForUpdate.add(updatedCi);
721 listForUpdate.add(origInst);
723 containerComponent.setComponentInstances(listForUpdate);
725 if (resultOp == null) {
726 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
727 if (updateStatus.isRight()) {
728 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
729 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
732 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
733 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
734 if (op.isPresent()) {
735 updatedList.add(updatedInstance);
741 resultOp = Either.left(updatedList);
746 unlockComponent(resultOp, containerComponent);
751 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
752 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
755 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
756 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
757 return ComponentTypeEnum.SERVICE_INSTANCE;
759 return ComponentTypeEnum.RESOURCE_INSTANCE;
763 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
764 ComponentInstance componentInstance) {
766 Either<ComponentInstance, ResponseFormat> resultOp = null;
767 Optional<ComponentInstance> componentInstanceOptional = null;
768 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
769 ComponentInstance oldComponentInstance = null;
770 boolean isNameChanged = false;
772 if (resultOp == null) {
773 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
774 if (!componentInstanceOptional.isPresent()) {
775 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
776 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
779 if (resultOp == null) {
780 oldComponentInstance = componentInstanceOptional.get();
781 String newInstanceName = componentInstance.getName();
782 if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
783 isNameChanged = true;
784 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
786 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);
787 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
790 if (resultOp == null) {
791 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
792 if (updateRes.isRight()) {
793 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
794 updateRes.right().value());
795 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
797 // region - Update instance Groups
799 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
800 if (result.isRight())
801 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
806 if (resultOp == null) {
807 String newInstanceId = updateRes.left().value().getRight();
808 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
810 if (!updatedInstanceOptional.isPresent()) {
811 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
812 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
814 resultOp = Either.left(updatedInstanceOptional.get());
818 if (resultOp == null) {
819 resultOp = Either.left(componentInstanceOptional.get());
826 * The normalized old vf name
827 * @param newNormailzedPrefix-
828 * The normalized new vf name
829 * @param qualifiedGroupInstanceName-
830 * old Group Instance Name
832 // modify group names
833 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
834 if (qualifiedGroupInstanceName == null) {
835 log.info("CANNOT change group name ");
838 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
839 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
840 return qualifiedGroupInstanceName;
843 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
844 oldComponentInstance.setName(newComponentInstance.getName());
845 oldComponentInstance.setModificationTime(System.currentTimeMillis());
846 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
847 if (oldComponentInstance.getGroupInstances() != null)
848 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
849 return oldComponentInstance;
852 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
854 validateUserExists(userId, "delete Component Instance", false);
856 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
857 if (validateComponentType.isRight()) {
858 return Either.right(validateComponentType.right().value());
861 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
862 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
863 if (validateComponentExists.isRight()) {
864 return Either.right(validateComponentExists.right().value());
866 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
867 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
868 if (validateCanWorkOnComponent.isRight()) {
869 return Either.right(validateCanWorkOnComponent.right().value());
872 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
873 if (lockComponent.isRight()) {
874 return Either.right(lockComponent.right().value());
877 Either<ComponentInstance, ResponseFormat> resultOp = null;
879 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
880 if (resultOp.isRight()){
883 Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
884 containerComponentType, resultOp);
885 if (deleteEither.isRight()){
891 unlockComponent(resultOp, containerComponent);
895 public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
896 Either<ComponentInstance, ResponseFormat> resultOp) {
897 if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
898 final ComponentInstance componentInstance = resultOp.left().value();
899 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
900 if (!pathIDsToBeDeleted.isEmpty()) {
901 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
903 if(deleteForwardingPathsEither.isRight()) {
904 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
913 private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
915 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
916 if(storageStatus.isRight()) {
917 return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
919 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
920 Sets.newHashSet(pathIdsToDelete));
922 if(result.isRight()) {
923 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
925 return Either.left(result.left().value());
928 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
929 ComponentParametersView filter = new ComponentParametersView(true);
930 filter.setIgnoreForwardingPath(false);
931 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
932 .getToscaElement(containerComponentId, filter);
933 Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
934 List<String> pathIDsToBeDeleted = new ArrayList<>();
936 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
937 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
939 return pathIDsToBeDeleted;
942 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
943 String componentInstanceId){
944 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
945 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
946 elementDataDefinition.getToNode()
947 .equalsIgnoreCase(componentInstanceId));
951 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
953 Either<ComponentInstance, ResponseFormat> resultOp = null;
954 ComponentInstance deletedInstance = null;
955 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
957 if (deleteRes.isRight()) {
958 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
959 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
960 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
962 if (resultOp == null) {
963 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
964 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
965 resultOp = Either.left(deletedInstance);
967 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
968 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
969 for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
970 Map<String, String> members = currGroup.getMembers();
971 if (members != null && members.containsKey(deletedInstance.getName())) {
972 members.remove(deletedInstance.getName());
973 groupsToUpdate.add(currGroup);
976 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
977 if (updateGroupsRes.isRight()) {
978 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
979 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
980 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
983 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
984 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
985 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
986 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
987 if (deleteInputsRes != StorageOperationStatus.OK) {
988 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
989 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
996 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
997 ComponentInstance foundInstance = null;
998 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
999 if (instance.getUniqueId().equals(componentInstanceId)) {
1000 foundInstance = instance;
1001 containerComponent.getComponentInstances().remove(instance);
1005 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1006 return foundInstance;
1009 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1010 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1011 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1015 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1016 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1019 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1020 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1023 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1024 boolean createNewTransaction) {
1026 validateUserExists(userId, "associate Ri To RI", inTransaction);
1028 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1030 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1031 if (validateComponentExists.isRight()) {
1032 return Either.right(validateComponentExists.right().value());
1034 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1036 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1037 if (validateCanWorkOnComponent.isRight()) {
1038 return Either.right(validateCanWorkOnComponent.right().value());
1041 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1043 if (lockComponent.isRight()) {
1044 return Either.right(lockComponent.right().value());
1050 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1056 unlockComponent(resultOp, containerComponent);
1060 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1062 log.debug("Try to create entry on graph");
1063 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1065 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1067 if (result.isLeft()) {
1068 log.debug("Enty on graph is created.");
1069 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1070 resultOp = Either.left(requirementCapabilityRelDef);
1074 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1075 String fromNameOrId = "";
1076 String toNameOrId = "";
1077 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1078 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1080 toNameOrId = requirementDef.getFromNode();
1081 fromNameOrId = requirementDef.getFromNode();
1082 if (fromResult.isLeft()) {
1083 fromNameOrId = fromResult.left().value().getName();
1085 if (toResult.isLeft()) {
1086 toNameOrId = toResult.left().value().getName();
1089 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1096 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1097 validateUserExists(userId, "dissociate RI From RI", false);
1099 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1100 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1101 if (validateComponentExists.isRight()) {
1102 return Either.right(validateComponentExists.right().value());
1104 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1106 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1107 if (validateCanWorkOnComponent.isRight()) {
1108 return Either.right(validateCanWorkOnComponent.right().value());
1110 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1112 if (lockComponent.isRight()) {
1113 return Either.right(lockComponent.right().value());
1116 log.debug("Try to create entry on graph");
1117 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1118 if (result.isLeft()) {
1119 log.debug("Enty on graph is created.");
1120 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1121 resultOp = Either.left(requirementCapabilityRelDef);
1126 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1127 String fromNameOrId = "";
1128 String toNameOrId = "";
1129 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1130 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1132 toNameOrId = requirementDef.getFromNode();
1133 fromNameOrId = requirementDef.getFromNode();
1134 if (fromResult.isLeft()) {
1135 fromNameOrId = fromResult.left().value().getName();
1137 if (toResult.isLeft()) {
1138 toNameOrId = toResult.left().value().getName();
1142 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1146 unlockComponent(resultOp, containerComponent);
1150 * Allows to get relation contained in specified component according to received Id
1151 * @param componentId
1154 * @param componentTypeEnum
1157 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1159 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1161 org.openecomp.sdc.be.model.Component containerComponent = null;
1162 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1163 RequirementCapabilityRelDef foundRelation = null;
1165 validateUserExists(userId, "get relation by Id", false);
1167 if(resultOp == null){
1168 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1169 if (validateComponentExists.isRight()) {
1170 resultOp = Either.right(validateComponentExists.right().value());
1173 if(resultOp == null){
1174 containerComponent = validateComponentExists.left().value();
1175 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1176 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1177 if(foundRelation == null){
1178 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1179 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1180 resultOp = Either.right(responseFormat);
1183 if(resultOp == null){
1184 resultOp = setRelatedCapability(foundRelation, containerComponent);
1186 if(resultOp.isLeft()){
1187 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1189 } catch (Exception e) {
1190 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1191 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1196 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1197 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1198 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1199 return relationship;
1205 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1206 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1207 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1208 String instanceId = foundRelation.getFromNode();
1209 Optional<RequirementDefinition> foundRequirement;
1210 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1211 if(!instance.isPresent()){
1212 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1213 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1214 result = Either.right(responseFormat);
1217 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1218 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1219 if(foundRequirement.isPresent()){
1220 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1221 result = Either.left(foundRelation);
1226 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1227 if(getfulfilledRequirementRes.isRight()){
1228 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1229 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1230 result = Either.right(responseFormat);
1232 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1236 result = Either.left(foundRelation);
1241 private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1242 return req.getName().equals(relationshipInfo.getRequirement()) &&
1243 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1244 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1247 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1248 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1249 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1250 String instanceId = foundRelation.getToNode();
1251 Optional<CapabilityDefinition> foundCapability;
1252 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1253 if(!instance.isPresent()){
1254 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1255 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1256 result = Either.right(responseFormat);
1259 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1260 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1261 if(foundCapability.isPresent()){
1262 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1263 result = Either.left(foundRelation);
1268 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1269 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1270 if(getfulfilledRequirementRes.isRight()){
1271 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1272 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1273 result = Either.right(responseFormat);
1275 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1279 result = Either.left(foundRelation);
1284 private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1285 return cap.getName().equals(relationshipInfo.getCapability()) &&
1286 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1287 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1290 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1291 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1292 Either<ComponentInstanceProperty, ResponseFormat> result;
1293 if (eitherAttribute.isLeft()) {
1294 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1295 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1297 result = Either.left(instanceAttribute);
1300 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1302 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1304 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1310 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1312 Either<ComponentInstanceProperty, ResponseFormat> result;
1314 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1315 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1316 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1318 if (!errorWrapper.isEmpty()) {
1319 result = Either.right(errorWrapper.getInnerElement());
1321 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1322 if (eitherAttribute.isLeft()) {
1323 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1324 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1325 result = Either.left(instanceAttribute);
1328 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1330 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1331 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1339 * Create Or Updates Attribute Instance
1341 * @param componentTypeEnum
1342 * @param componentId
1343 * @param resourceInstanceId
1348 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1349 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1350 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1352 validateUserExist(userId, "create Or Update Attribute Value");
1353 if (errorWrapper.isEmpty()) {
1354 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1356 if (errorWrapper.isEmpty()) {
1357 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1359 if (errorWrapper.isEmpty()) {
1360 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1364 if (errorWrapper.isEmpty()) {
1365 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1367 result = createAttributeValue(attribute, resourceInstanceId);
1369 result = updateAttributeValue(attribute, resourceInstanceId);
1372 result = Either.right(errorWrapper.getInnerElement());
1378 if (result == null || result.isRight()) {
1379 titanDao.rollback();
1384 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1388 private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1389 return StringUtils.isNotEmpty(property.getValue())
1390 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1391 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1394 // US833308 VLI in service - specific network_role property value logic
1395 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1396 for (ComponentInstanceProperty property: properties) {
1397 if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1398 ComponentParametersView componentParametersView = new ComponentParametersView();
1399 componentParametersView.disableAll();
1400 componentParametersView.setIgnoreComponentInstances(false);
1401 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1402 if (getServiceResult.isRight()) {
1403 return getServiceResult.right().value();
1405 Component service = getServiceResult.left().value();
1406 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1407 if (!getInstance.isPresent()) {
1408 return StorageOperationStatus.NOT_FOUND;
1410 String prefix = service.getSystemName() + ".";
1411 String value = property.getValue();
1412 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1413 property.setValue(prefix + value);
1417 return StorageOperationStatus.OK;
1420 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1422 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1424 /*-------------------------------Validations---------------------------------*/
1426 validateUserExists(userId, "create Or Update Properties Values", false);
1428 if (componentTypeEnum == null) {
1429 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO);
1430 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1433 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1435 if (getResourceResult.isRight()) {
1436 log.debug("Failed to retrieve component, component id {}", componentId);
1437 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1440 Component containerComponent = getResourceResult.left().value();
1442 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1443 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1444 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1447 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1448 if (resourceInstanceStatus.isRight()) {
1449 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1452 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1453 // specific property value logic US833308
1454 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1455 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1456 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1460 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1461 if (lockStatus != StorageOperationStatus.OK) {
1462 log.debug("Failed to lock service {}", componentId);
1463 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1468 for (ComponentInstanceProperty property: properties) {
1469 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1470 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1471 responseFormat -> Either.right(responseFormat));
1474 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1475 if (updateContainerRes.isRight()) {
1476 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1477 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1480 resultOp = Either.left(properties);
1484 if (resultOp == null || resultOp.isRight()) {
1485 titanDao.rollback();
1490 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1494 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1495 String capabilityType, String capabilityName) {
1496 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1497 StringBuffer sb = new StringBuffer(componentInstanceUniqueId);
1498 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1499 String capKey = sb.toString();
1501 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1502 .orElse(Collections.emptyMap());
1503 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1504 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1505 if (cap.isPresent()) {
1506 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1507 if (capProperties != null) {
1508 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1509 StorageOperationStatus status;
1510 if (instanceProperty.isPresent()) {
1511 instanceProperty.get().setValue(newValue);
1512 List<String> path = new ArrayList<>();
1513 path.add(componentInstanceUniqueId);
1515 instanceProperty.get().setPath(path);
1516 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1517 if (status != StorageOperationStatus.OK) {
1518 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1519 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1522 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1528 return componentsUtils.getResponseFormat(ActionStatus.OK);
1531 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1532 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1533 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1534 StorageOperationStatus status;
1535 instanceProperty.get().setValue(newValue);
1536 if (instanceProperty.isPresent()) {
1537 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1539 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1541 if (status != StorageOperationStatus.OK) {
1542 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1543 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1545 List<String> path = new ArrayList<>();
1546 path.add(foundResourceInstance.getUniqueId());
1547 property.setPath(path);
1549 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1550 return componentsUtils.getResponseFormat(ActionStatus.OK);
1553 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1554 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1555 if (allDataTypesEither.isRight()) {
1556 TitanOperationStatus status = allDataTypesEither.right().value();
1557 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1558 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1560 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1561 String innerType = null;
1562 String propertyType = property.getType();
1563 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1564 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1566 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1567 SchemaDefinition def = property.getSchema();
1569 log.debug("Schema doesn't exists for property of type {}", type);
1570 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1572 PropertyDataDefinition propDef = def.getProperty();
1573 if (propDef == null) {
1574 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1575 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1577 innerType = propDef.getType();
1579 // Specific Update Logic
1580 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1581 String newValue = property.getValue();
1582 if (isValid.isRight()) {
1583 Boolean res = isValid.right().value();
1585 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1588 Object object = isValid.left().value();
1589 if (object != null) {
1590 newValue = object.toString();
1594 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1595 if (pair.getRight() != null && pair.getRight() == false) {
1596 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1597 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1600 return Either.left(newValue);
1603 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1604 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1605 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1606 StorageOperationStatus status;
1607 if (instanceProperty.isPresent()) {
1608 instanceProperty.get().setValue(input.getValue());
1609 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1611 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1613 if (status != StorageOperationStatus.OK) {
1614 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1615 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1617 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1618 return componentsUtils.getResponseFormat(ActionStatus.OK);
1621 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1623 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1625 validateUserExists(userId, "create Or Update Property Value", false);
1627 if (componentTypeEnum == null) {
1628 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1629 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1632 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1634 if (getResourceResult.isRight()) {
1635 log.debug("Failed to retrieve component, component id {}", componentId);
1636 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1639 Component containerComponent = getResourceResult.left().value();
1641 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1642 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1643 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1646 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1647 if (resourceInstanceStatus.isRight()) {
1648 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1652 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1655 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1656 if (lockStatus != StorageOperationStatus.OK) {
1657 log.debug("Failed to lock service {}", componentId);
1658 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1662 for (ComponentInstanceInput input: inputs) {
1663 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1664 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1665 responseFormat -> Either.right(responseFormat));
1668 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1670 if (updateContainerRes.isRight()) {
1671 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1672 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1675 resultOp = Either.left(inputs);
1679 if (resultOp == null || resultOp.isRight()) {
1680 titanDao.rollback();
1685 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1690 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1693 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1695 validateUserExists(userId, "create Or Update Property Value", false);
1697 if (componentTypeEnum == null) {
1698 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1699 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1703 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1704 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1705 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1709 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1710 if (lockStatus != StorageOperationStatus.OK) {
1711 log.debug("Failed to lock service {}", componentId);
1712 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1716 String propertyValueUid = property.getValueUniqueUid();
1718 if (propertyValueUid == null) {
1720 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1722 if (counterRes.isRight()) {
1723 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1724 StorageOperationStatus status = counterRes.right().value();
1725 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1726 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1728 Integer index = counterRes.left().value();
1729 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1731 if (result.isLeft()) {
1732 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1733 ComponentInstanceProperty instanceProperty = result.left().value();
1735 resultOp = Either.left(instanceProperty);
1738 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1740 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1742 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1746 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1748 if (result.isLeft()) {
1749 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1750 ComponentInstanceProperty instanceProperty = result.left().value();
1752 resultOp = Either.left(instanceProperty);
1755 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1757 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1759 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1762 if (resultOp.isLeft()) {
1763 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1764 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1765 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1767 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1774 if (resultOp == null || resultOp.isRight()) {
1775 titanDao.rollback();
1780 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1785 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1787 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1789 validateUserExists(userId, "create Or Update Input Value", false);
1791 if (componentTypeEnum == null) {
1792 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1793 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1797 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1798 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1799 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1803 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1804 if (lockStatus != StorageOperationStatus.OK) {
1805 log.debug("Failed to lock service {}", componentId);
1806 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1810 String propertyValueUid = inputProperty.getValueUniqueUid();
1811 if (propertyValueUid == null) {
1813 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1815 if (counterRes.isRight()) {
1816 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1817 StorageOperationStatus status = counterRes.right().value();
1818 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1819 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1821 Integer index = counterRes.left().value();
1822 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1824 if (result.isLeft()) {
1825 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1826 ComponentInstanceInput instanceProperty = result.left().value();
1828 resultOp = Either.left(instanceProperty);
1832 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1834 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1836 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1842 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1844 if (result.isLeft()) {
1845 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1846 ComponentInstanceInput instanceProperty = result.left().value();
1848 resultOp = Either.left(instanceProperty);
1852 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1854 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1856 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1863 if (resultOp == null || resultOp.isRight()) {
1864 titanDao.rollback();
1869 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1874 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1876 validateUserExists(userId, "delete Property Value", false);
1878 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1880 if (componentTypeEnum == null) {
1881 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1882 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1886 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1887 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1888 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1892 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1893 if (lockStatus != StorageOperationStatus.OK) {
1894 log.debug("Failed to lock service {}", serviceId);
1895 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1899 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1901 if (result.isLeft()) {
1902 log.debug("Property value {} was removed from graph.", propertyValueId);
1903 ComponentInstanceProperty instanceProperty = result.left().value();
1905 resultOp = Either.left(instanceProperty);
1909 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1911 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1913 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1919 if (resultOp == null || resultOp.isRight()) {
1920 titanDao.rollback();
1925 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1930 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1932 Either<Component, ResponseFormat> eitherResponse = null;
1933 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1934 Component component;
1935 ResponseFormat errorResponse;
1936 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1937 if (getComponentRes.isRight()) {
1938 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1939 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1940 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1941 eitherResponse = Either.right(errorResponse);
1943 if (eitherResponse == null) {
1944 component = getComponentRes.left().value();
1945 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1946 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1947 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1948 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1949 eitherResponse = Either.right(errorResponse);
1952 if (eitherResponse == null) {
1953 eitherResponse = Either.left(getComponentRes.left().value());
1955 return eitherResponse;
1958 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
1959 String containerComponentId,
1960 String componentInstanceId,
1961 ComponentInstance newComponentInstance) {
1962 Either<Set<String>, ResponseFormat> resultOp;
1963 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1964 if (validateComponentType.isRight()) {
1965 return Either.right(validateComponentType.right().value());
1967 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1968 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
1971 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
1972 validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
1973 if (validateComponentExists.isRight()) {
1974 return Either.right(validateComponentExists.right().value());
1976 Component containerComponent = validateComponentExists.left().value();
1978 //Fetch current component instance
1979 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
1980 getResourceInstanceById(containerComponent, componentInstanceId);
1981 if (eitherResourceInstance.isRight()) {
1982 resultOp = Either.right(componentsUtils.getResponseFormat(
1983 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
1986 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
1988 //Check whether new componentInstance exists
1989 String resourceId = newComponentInstance.getComponentUid();
1990 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
1991 if (componentExistsRes.isRight()) {
1992 log.debug("Failed to find resource ", resourceId);
1993 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
1994 (componentExistsRes.right().value()), resourceId));
1996 } else if (!componentExistsRes.left().value()) {
1997 log.debug("The resource {} not found ", resourceId);
1998 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2002 //Fetch component using new component instance uid
2003 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2004 if (eitherResourceName.isRight()) {
2005 resultOp = Either.right(eitherResourceName.right().value());
2008 Component updatedContainerComponent=eitherResourceName.left().value();
2009 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2010 currentResourceInstance, updatedContainerComponent);
2011 resultOp=Either.left(toDeleteForwardingPaths);
2016 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2017 Component updatedContainerComponent) {
2018 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2019 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2021 Service service = (Service) containerComponent;
2022 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2024 return forwardingPathUtils.
2025 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2028 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2029 ComponentParametersView componentParametersView = new ComponentParametersView();
2030 componentParametersView.setIgnoreCapabiltyProperties(false);
2031 componentParametersView.setIgnoreForwardingPath(false);
2032 return componentParametersView;
2035 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2037 User user = validateUserExists(userId, "change Component Instance Version", false);
2039 Either<ComponentInstance, ResponseFormat> resultOp = null;
2041 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2042 if (validateComponentType.isRight()) {
2043 return Either.right(validateComponentType.right().value());
2046 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2047 ComponentParametersView componentParametersView = new ComponentParametersView();
2048 componentParametersView.setIgnoreCapabiltyProperties(false);
2049 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2050 if (validateComponentExists.isRight()) {
2051 return Either.right(validateComponentExists.right().value());
2053 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2055 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2056 if (validateCanWorkOnComponent.isRight()) {
2057 return Either.right(validateCanWorkOnComponent.right().value());
2060 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2061 if (resourceInstanceStatus.isRight()) {
2062 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2066 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2068 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2071 public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2072 ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
2073 Either<ComponentInstance, ResponseFormat> resultOp = null;
2074 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2076 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2077 String containerComponentId = containerComponent.getUniqueId();
2078 String componentInstanceId = currentResourceInstance.getUniqueId();
2079 if (lockComponent.isRight()) {
2080 return Either.right(lockComponent.right().value());
2086 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2087 resultOp = Either.left(currentResourceInstance);
2091 String resourceId = newComponentInstance.getComponentUid();
2095 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2096 if (componentExistsRes.isRight()) {
2097 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2098 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2100 } else if (!componentExistsRes.left().value()) {
2101 log.debug("The resource {} not found ", resourceId);
2102 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2106 Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2108 if (eitherOriginComponent.isRight()) {
2109 resultOp = Either.right(eitherOriginComponent.right().value());
2112 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2113 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2114 if (resultOp.isRight()) {
2115 log.debug("failed to delete resource instance {}", resourceId);
2118 ComponentInstance resResourceInfo = resultOp.left().value();
2119 Component origComponent = null;
2120 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2121 if (originType == OriginTypeEnum.ServiceProxy) {
2122 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2123 if (serviceProxyOrigin.isRight()) {
2124 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2125 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2127 origComponent = serviceProxyOrigin.left().value();
2129 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2131 if (fillProxyRes != StorageOperationStatus.OK) {
2132 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2133 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2136 newComponentInstance.setOriginType(originType);
2140 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2142 if (eitherResourceName.isRight()) {
2143 resultOp = Either.right(eitherResourceName.right().value());
2147 origComponent = eitherResourceName.left().value();
2149 newComponentInstance.setName(resResourceInfo.getName());
2152 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2153 newComponentInstance.setPosX(resResourceInfo.getPosX());
2154 newComponentInstance.setPosY(resResourceInfo.getPosY());
2155 newComponentInstance.setDescription(resResourceInfo.getDescription());
2157 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2159 if (resultOp.isRight()) {
2160 log.debug("failed to create resource instance {}", resourceId);
2164 ComponentInstance updatedComponentInstance = resultOp.left().value();
2165 if (resultOp.isRight()) {
2166 log.debug("failed to create resource instance {}", resourceId);
2170 Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2171 if (mergeStatusEither.isRight()) {
2172 return Either.right(mergeStatusEither.right().value());
2175 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2176 if (postChangeVersionResult != ActionStatus.OK) {
2177 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2180 ComponentParametersView filter = new ComponentParametersView(true);
2181 filter.setIgnoreComponentInstances(false);
2182 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2183 if (updatedComponentRes.isRight()) {
2184 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2185 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2186 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2187 log.debug("Component with id {} was not found", containerComponentId);
2188 return Either.right(responseFormat);
2190 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2191 if (resourceInstanceStatus.isRight()) {
2192 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2195 resultOp = Either.left(resourceInstanceStatus.left().value());
2199 unlockComponent(resultOp, containerComponent);
2204 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2205 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2206 Component containerComponent = null;
2208 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2210 validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2212 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2213 if (validateComponentType.isRight()) {
2214 resultOp = Either.right(validateComponentType.right().value());
2218 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2219 if (validateContainerComponentExists.isRight()) {
2220 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2223 containerComponent = validateContainerComponentExists.left().value();
2225 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2226 if (resourceInstanceStatus.isRight()) {
2227 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2231 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2232 if (CollectionUtils.isEmpty(instanceProperties)) {
2233 instanceProperties = new ArrayList<>();
2235 resultOp = Either.left(instanceProperties);
2238 unlockComponent(resultOp, containerComponent);
2242 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2243 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2245 if (counterRes.isRight()) {
2246 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2247 StorageOperationStatus status = counterRes.right().value();
2248 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2249 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2251 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2257 * updates componentInstance modificationTime
2259 * @param componentInstance
2260 * @param componentInstanceType
2261 * @param modificationTime
2262 * @param inTransaction
2265 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2266 Either<ComponentInstanceData, ResponseFormat> result;
2267 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2269 if (updateComponentInstanceRes.isRight()) {
2270 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2271 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2273 result = Either.left(updateComponentInstanceRes.left().value());
2278 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2279 // TODO Add implementation
2280 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2284 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2285 // TODO Add implementation
2286 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2290 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2291 // TODO Add implementation
2292 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2296 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2297 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2300 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2302 Either<ComponentInstance, StorageOperationStatus> result = null;
2303 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2304 Optional<ComponentInstance> foundInstance = null;
2305 if (CollectionUtils.isEmpty(instances)) {
2306 result = Either.right(StorageOperationStatus.NOT_FOUND);
2308 if (result == null) {
2309 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2310 if (!foundInstance.isPresent()) {
2311 result = Either.right(StorageOperationStatus.NOT_FOUND);
2314 if (result == null) {
2315 result = Either.left(foundInstance.get());
2320 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2322 Long creationDate = origInstanceForUpdate.getCreationTime();
2324 Long modificationTime = System.currentTimeMillis();
2325 resourceInstanceForUpdate.setCreationTime(creationDate);
2326 resourceInstanceForUpdate.setModificationTime(modificationTime);
2328 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2330 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2331 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2334 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2336 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2337 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2339 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2340 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2342 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2343 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2345 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2346 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2348 if (resourceInstanceForUpdate.getOriginType() == null) {
2349 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2351 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2352 resourceInstanceForUpdate.setIsProxy(true);
2353 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2354 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2356 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2357 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2359 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2360 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2362 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2363 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2365 return resourceInstanceForUpdate;
2368 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2369 * @param containerComponentType
2370 * @param containerComponentId
2371 * @param componentInstanceUniqueId
2372 * @param capabilityType
2373 * @param capabilityName
2378 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2380 Component containerComponent = null;
2382 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2384 validateUserExists(userId, "Get Component Instance Properties By Id", false);
2385 if(resultOp == null){
2386 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2387 if (validateComponentType.isRight()) {
2388 resultOp = Either.right(validateComponentType.right().value());
2391 if(resultOp == null){
2392 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2393 if (validateContainerComponentExists.isRight()) {
2394 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2396 containerComponent = validateContainerComponentExists.left().value();
2399 if(resultOp == null){
2400 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2401 if (resourceInstanceStatus.isRight()) {
2402 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2404 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2409 unlockComponent(resultOp, containerComponent);
2413 private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2414 Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2415 CapabilityDefinition foundCapability;
2416 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2417 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2418 if (capabilitiesPerType != null) {
2419 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2420 if (capabilityOpt.isPresent()) {
2421 foundCapability = capabilityOpt.get();
2422 result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2426 if (result == null) {
2427 result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2432 private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2433 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2435 Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2436 if(getComponentInstanceCapabilityProperties.isRight()){
2437 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2439 resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
2441 } catch(Exception e){
2442 log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2443 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2448 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2449 String capabilityType, String capabilityName, String ownerId) {
2450 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2451 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2452 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2453 String capKey = sb.toString();
2455 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2456 .orElse(Collections.emptyMap());
2457 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2458 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2459 if (cap.isPresent()) {
2460 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2461 if (capProperties != null) {
2462 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2463 StorageOperationStatus status;
2464 if (instanceProperty.isPresent()) {
2465 instanceProperty.get().setValue(newValue);
2466 List<String> path = new ArrayList<>();
2467 path.add(componentInstanceUniqueId);
2469 instanceProperty.get().setPath(path);
2470 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2471 if (status != StorageOperationStatus.OK) {
2472 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2473 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2476 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2480 return componentsUtils.getResponseFormat(ActionStatus.OK);
2483 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2484 List<ComponentInstanceProperty> properties, String userId) {
2485 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2487 validateUserExists(userId, "update instance capability property", false);
2489 if (componentTypeEnum == null) {
2490 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2491 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2493 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2495 if (getResourceResult.isRight()) {
2496 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2497 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2499 Component containerComponent = getResourceResult.left().value();
2501 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2502 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2503 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2505 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2506 if (resourceInstanceStatus.isRight()) {
2507 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2509 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2511 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2512 if (lockStatus != StorageOperationStatus.OK) {
2513 log.debug("Failed to lock component {}", containerComponentId);
2514 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2517 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2518 if (allDataTypes.isRight()) {
2519 TitanOperationStatus status = allDataTypes.right().value();
2520 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2521 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2525 for (ComponentInstanceProperty property : properties) {
2526 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2527 newPropertyValueEither.bimap(updatedValue ->
2528 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2529 responseFormat -> Either.right(responseFormat));
2531 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2533 if (updateContainerRes.isRight()) {
2534 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2535 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2538 resultOp = Either.left(properties);
2542 if (resultOp == null || resultOp.isRight()) {
2543 titanDao.rollback();
2548 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2552 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2553 List<ComponentInstanceProperty> properties, String userId) {
2554 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2556 validateUserExists(userId, "update instance capability property", false);
2558 if (componentTypeEnum == null) {
2559 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2560 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2562 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2564 if (getResourceResult.isRight()) {
2565 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2566 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2568 Component containerComponent = getResourceResult.left().value();
2570 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2571 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2572 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2574 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2575 if (resourceInstanceStatus.isRight()) {
2576 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2578 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2580 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2581 if (lockStatus != StorageOperationStatus.OK) {
2582 log.debug("Failed to lock component {}", containerComponentId);
2583 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2587 for (ComponentInstanceProperty property : properties) {
2588 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2589 newPropertyValueEither.bimap(updatedValue ->
2590 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2591 responseFormat -> Either.right(responseFormat));
2593 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2595 if (updateContainerRes.isRight()) {
2596 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2597 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2600 resultOp = Either.left(properties);
2604 if (resultOp == null || resultOp.isRight()) {
2605 titanDao.rollback();
2610 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());