2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.collect.Sets;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.components.impl.version.PostChangeVersionOperationOrchestrator;
30 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
31 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
32 import org.openecomp.sdc.be.components.validation.ComponentValidations;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
35 import org.openecomp.sdc.be.dao.api.ActionStatus;
36 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
37 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
38 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
39 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
40 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
41 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
48 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
49 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
50 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
51 import org.openecomp.sdc.be.model.*;
52 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
53 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
54 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
55 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
56 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
57 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
58 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
59 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
60 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
61 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
62 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
63 import org.openecomp.sdc.common.api.Constants;
64 import org.openecomp.sdc.common.datastructure.Wrapper;
65 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
66 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
67 import org.openecomp.sdc.common.util.ValidationUtils;
68 import org.openecomp.sdc.exception.ResponseFormat;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.springframework.beans.factory.annotation.Autowired;
74 import java.util.Map.Entry;
75 import java.util.function.BiConsumer;
76 import java.util.stream.Collectors;
78 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
80 @org.springframework.stereotype.Component
81 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
83 private static final Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class);
86 private IComponentInstanceOperation componentInstanceOperation;
89 private ArtifactsBusinessLogic artifactBusinessLogic;
92 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
95 private PostChangeVersionOperationOrchestrator postChangeVersionOperationOrchestrator;
97 public static final String VF_MODULE = "org.openecomp.groups.VfModule";
99 public ComponentInstanceBusinessLogic() {
102 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
103 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
106 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
107 List<ComponentInstanceProperty> resList = new ArrayList<>();
108 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
109 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
110 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
112 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
114 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
116 ciName = ciOp.get().getName();
117 if (ciPropList != null && !ciPropList.isEmpty()) {
118 for(ComponentInstanceProperty prop: ciPropList){
119 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
120 if(inputsValues != null && !inputsValues.isEmpty()){
121 for(GetInputValueDataDefinition inputData: inputsValues){
122 if(isGetInputValueForInput(inputData, inputId)){
123 prop.setComponentInstanceId(s);
124 prop.setComponentInstanceName(ciName);
140 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
141 List<ComponentInstanceInput> resList = new ArrayList<>();
142 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
143 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
144 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
146 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
148 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
150 ciName = ciOp.get().getName();
151 if (ciPropList != null && !ciPropList.isEmpty()) {
152 for(ComponentInstanceInput prop: ciPropList){
153 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
154 if(inputsValues != null && !inputsValues.isEmpty()){
155 for(GetInputValueDataDefinition inputData: inputsValues){
156 if(isGetInputValueForInput(inputData, inputId)){
157 prop.setComponentInstanceId(s);
158 prop.setComponentInstanceName(ciName);
174 public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
176 Component origComponent = null;
177 Either<ComponentInstance, ResponseFormat> resultOp = null;
179 org.openecomp.sdc.be.model.Component containerComponent = null;
180 ComponentTypeEnum containerComponentType;
183 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
184 if (resp.isRight()) {
185 return Either.right(resp.right().value());
187 user = resp.left().value();
190 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
191 if (validateValidJson.isRight()) {
192 return Either.right(validateValidJson.right().value());
195 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
196 if (validateComponentType.isRight()) {
197 return Either.right(validateComponentType.right().value());
199 containerComponentType = validateComponentType.left().value();
202 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
203 if (validateComponentExists.isRight()) {
204 return Either.right(validateComponentExists.right().value());
206 containerComponent = validateComponentExists.left().value();
209 if (ModelConverter.isAtomicComponent(containerComponent)) {
210 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
211 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
214 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
215 if (validateCanWorkOnComponent.isRight()) {
216 return Either.right(validateCanWorkOnComponent.right().value());
219 if (resourceInstance != null && containerComponentType != null) {
220 OriginTypeEnum originType = resourceInstance.getOriginType();
221 if (originType == OriginTypeEnum.ServiceProxy) {
222 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
223 if (serviceProxyOrigin.isRight()) {
224 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
225 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
227 origComponent = serviceProxyOrigin.left().value();
229 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
230 if (fillProxyRes != StorageOperationStatus.OK) {
231 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
232 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
237 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
239 if (getOriginComponentRes.isRight()) {
240 return Either.right(getOriginComponentRes.right().value());
242 origComponent = getOriginComponentRes.left().value();
247 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
248 if (lockComponent.isRight()) {
249 return Either.right(lockComponent.right().value());
252 log.debug("Try to create entry on graph");
253 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
258 unlockComponent(resultOp, containerComponent);
262 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
263 resourceInstance.setIsProxy(true);
264 ComponentParametersView filter = new ComponentParametersView(true);
265 filter.setIgnoreCapabilities(false);
266 filter.setIgnoreCapabiltyProperties(false);
267 filter.setIgnoreComponentInstances(false);
268 filter.setIgnoreRequirements(false);
269 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
270 if (serviceRes.isRight()) {
271 return serviceRes.right().value();
273 Component service = serviceRes.left().value();
274 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
275 resourceInstance.setCapabilities(capabilities);
276 Map<String, List<RequirementDefinition>> req = service.getRequirements();
277 resourceInstance.setRequirements(req);
279 String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
280 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
281 int lastIndexOf = toscaResourceName.lastIndexOf('.');
282 if (lastIndexOf != -1) {
283 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
284 resourceInstance.setToscaComponentName(proxyToscaName);
286 resourceInstance.setName(name);
287 resourceInstance.setIsProxy(true);
288 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
289 resourceInstance.setSourceModelName(service.getName());
290 resourceInstance.setSourceModelUuid(service.getUUID());
291 resourceInstance.setSourceModelUid(service.getUniqueId());
292 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
293 resourceInstance.setDescription("A Proxy for Service " + service.getName());
294 resourceInstance.setComponentVersion(service.getVersion());
296 return StorageOperationStatus.OK;
299 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
301 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
302 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
303 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
305 Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
306 if (resp.isRight()) {
307 return Either.right(resp.right().value());
310 User user = resp.left().value();
311 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
312 if (validateComponentType.isRight()) {
313 return Either.right(validateComponentType.right().value());
316 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
318 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
319 if (validateComponentExists.isRight()) {
320 return Either.right(validateComponentExists.right().value());
322 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
324 if (ModelConverter.isAtomicComponent(containerComponent)) {
325 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
326 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
329 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
330 if (validateCanWorkOnComponent.isRight()) {
331 return Either.right(validateCanWorkOnComponent.right().value());
334 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
335 if (lockComponent.isRight()) {
336 return Either.right(lockComponent.right().value());
340 log.debug("Try to create entry on graph");
341 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
343 if (eitherResourceName.isRight()) {
344 resultOp = Either.right(eitherResourceName.right().value());
347 Component origComponent = eitherResourceName.left().value();
349 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
350 if (result.isRight()) {
351 log.debug("Failed to create resource instance {}", containerComponentId);
352 resultOp = Either.right(result.right().value());
357 log.debug("Entity on graph is created.");
358 ComponentInstance resResourceInfo = result.left().value();
359 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
360 associationInfo.setFromNode(resResourceInfo.getUniqueId());
362 associationInfo.setToNode(resResourceInfo.getUniqueId());
365 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
366 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
367 if (resultReqCapDef.isLeft()) {
368 log.debug("Enty on graph is created.");
369 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
370 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
371 resultOp = Either.left(resInfo);
375 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
376 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
381 unlockComponent(resultOp, containerComponent);
385 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
386 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
389 private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
390 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
393 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
394 Either<Component, ResponseFormat> eitherResponse;
395 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
396 if (eitherComponent.isRight()) {
397 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
398 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
400 eitherResponse = Either.left(eitherComponent.left().value());
402 return eitherResponse;
405 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
406 Either<ComponentInstance, ResponseFormat> resultOp;
408 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
410 if (result.isRight()) {
411 log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
412 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
416 log.debug("Entity on graph is created.");
417 Component updatedComponent = result.left().value().getLeft();
418 Map<String, String> existingEnvVersions = new HashMap<>();
419 // TODO existingEnvVersions ??
420 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
421 if (addComponentInstanceArtifacts.isRight()) {
422 log.debug("Failed to create component instance {}", componentInstance.getName());
423 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
427 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
428 if (!updatedInstanceOptional.isPresent()) {
429 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
430 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
433 resultOp = Either.left(updatedInstanceOptional.get());
438 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
439 * @param containerComponent
440 * @param componentInstance
441 * @param originComponent
443 * @param existingEnvVersions
446 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) {
448 log.debug("add artifacts to resource instance");
449 List<GroupDefinition> filteredGroups = null;
450 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
451 if (!ActionStatus.OK.equals(status)) {
452 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
453 return Either.right(resultOp);
455 StorageOperationStatus artStatus;
456 // generate heat_env if necessary
457 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
458 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
460 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
461 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
463 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
464 String type = artifact.getArtifactType();
465 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
466 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
468 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
471 if (artifact.checkEsIdExist()) {
472 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
473 componentInstance.getName(), user, containerComponent, existingEnvVersions);
474 if (createHeatEnvPlaceHolder.isRight()) {
475 return Either.right(createHeatEnvPlaceHolder.right().value());
477 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
479 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
481 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
482 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
484 if (CollectionUtils.isNotEmpty(filteredGroups)) {
485 for (GroupDefinition groupInstance : filteredGroups) {
486 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
487 if (op.isPresent()) {
488 List<ArtifactDefinition> artifactsUid;
489 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
490 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
492 artifactsUid = new ArrayList<>();
494 artifactsUid.add(artifactDefinition);
495 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
502 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
503 if (artStatus != StorageOperationStatus.OK) {
504 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
505 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
508 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
509 if (result != StorageOperationStatus.OK) {
510 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
511 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
513 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
516 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
517 if (artStatus != StorageOperationStatus.OK) {
518 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
519 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
522 componentInstance.setArtifacts(originComponent.getArtifacts());
523 return Either.left(ActionStatus.OK);
526 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
527 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
529 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
530 if (getResourceDeploymentArtifacts.isRight()) {
531 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
532 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
533 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
534 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
537 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
540 if (!deploymentArtifacts.isEmpty()) {
541 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
542 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
543 if (!artifact.getValue().checkEsIdExist()) {
544 tempDeploymentArtifacts.remove(artifact.getKey());
548 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
551 return ActionStatus.OK;
554 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
555 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
558 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
559 boolean needLock, boolean createNewTransaction) {
561 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
562 if (resp.isRight()) {
563 return Either.right(resp.right().value());
566 Either<ComponentInstance, ResponseFormat> resultOp = null;
568 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
569 if (validateComponentType.isRight()) {
570 return Either.right(validateComponentType.right().value());
573 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
575 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
576 if (validateComponentExists.isRight()) {
577 return Either.right(validateComponentExists.right().value());
579 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
581 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
582 if (validateCanWorkOnComponent.isRight()) {
583 return Either.right(validateCanWorkOnComponent.right().value());
585 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
586 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
587 if (validateParentStatus.isRight()) {
588 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
589 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
592 if (!validateParentStatus.left().value()) {
593 resultOp = Either.right(
594 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
599 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
600 if (lockComponent.isRight()) {
601 return Either.right(lockComponent.right().value());
606 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
608 if (eitherResourceName.isRight()) {
609 resultOp = Either.right(eitherResourceName.right().value());
612 Component origComponent = eitherResourceName.left().value();
614 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
619 unlockComponent(resultOp, containerComponent);
623 // New Multiple Instance Update API
624 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
625 boolean createNewTransaction) {
627 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
628 org.openecomp.sdc.be.model.Component containerComponent = null;
630 Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
631 if (resp.isRight()) {
632 return Either.right(resp.right().value());
635 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
636 if (validateComponentType.isRight()) {
637 return Either.right(validateComponentType.right().value());
640 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
642 ComponentParametersView componentFilter = new ComponentParametersView();
643 componentFilter.disableAll();
644 componentFilter.setIgnoreUsers(false);
645 componentFilter.setIgnoreComponentInstances(false);
646 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
647 if (validateComponentExists.isRight()) {
648 return Either.right(validateComponentExists.right().value());
651 containerComponent = validateComponentExists.left().value();
653 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
654 if (validateCanWorkOnComponent.isRight()) {
655 return Either.right(validateCanWorkOnComponent.right().value());
658 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
660 for (ComponentInstance componentInstance : componentInstanceList) {
661 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
662 if (!validateParent) {
663 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
664 containerComponentId));
671 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
672 if (lockComponent.isRight()) {
673 return Either.right(lockComponent.right().value());
677 List<ComponentInstance> updatedList = new ArrayList<>();
678 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
679 List<ComponentInstance> listForUpdate = new ArrayList<>();
680 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
681 containerComponent.setComponentInstances(componentInstanceList);
683 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
684 while (iterator.hasNext()) {
685 ComponentInstance origInst = iterator.next();
686 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
687 if (op.isPresent()) {
688 ComponentInstance updatedCi = op.get();
689 updatedCi = buildComponentInstance(updatedCi, origInst);
691 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
693 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());
694 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
698 listForUpdate.add(updatedCi);
700 listForUpdate.add(origInst);
702 containerComponent.setComponentInstances(listForUpdate);
704 if (resultOp == null) {
705 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
706 if (updateStatus.isRight()) {
707 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
708 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
711 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
712 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
713 if (op.isPresent()) {
714 updatedList.add(updatedInstance);
720 resultOp = Either.left(updatedList);
725 unlockComponent(resultOp, containerComponent);
730 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
731 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
734 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
735 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
736 return ComponentTypeEnum.SERVICE_INSTANCE;
738 return ComponentTypeEnum.RESOURCE_INSTANCE;
742 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
743 ComponentInstance componentInstance) {
745 Either<ComponentInstance, ResponseFormat> resultOp = null;
746 Optional<ComponentInstance> componentInstanceOptional = null;
747 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
748 ComponentInstance oldComponentInstance = null;
749 boolean isNameChanged = false;
751 if (resultOp == null) {
752 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
753 if (!componentInstanceOptional.isPresent()) {
754 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
755 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
758 if (resultOp == null) {
759 oldComponentInstance = componentInstanceOptional.get();
760 String newInstanceName = componentInstance.getName();
761 if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
762 isNameChanged = true;
763 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
765 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);
766 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
769 if (resultOp == null) {
770 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
771 if (updateRes.isRight()) {
772 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
773 updateRes.right().value());
774 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
776 // region - Update instance Groups
778 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
779 if (result.isRight())
780 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
785 if (resultOp == null) {
786 String newInstanceId = updateRes.left().value().getRight();
787 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
789 if (!updatedInstanceOptional.isPresent()) {
790 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
791 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
793 resultOp = Either.left(updatedInstanceOptional.get());
797 if (resultOp == null) {
798 resultOp = Either.left(componentInstanceOptional.get());
805 * The normalized old vf name
806 * @param newNormailzedPrefix-
807 * The normalized new vf name
808 * @param qualifiedGroupInstanceName-
809 * old Group Instance Name
811 // modify group names
812 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
813 if (qualifiedGroupInstanceName == null) {
814 log.info("CANNOT change group name ");
817 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
818 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
819 return qualifiedGroupInstanceName;
822 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
823 oldComponentInstance.setName(newComponentInstance.getName());
824 oldComponentInstance.setModificationTime(System.currentTimeMillis());
825 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
826 if (oldComponentInstance.getGroupInstances() != null)
827 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
828 return oldComponentInstance;
831 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
833 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
834 if (resp.isRight()) {
835 return Either.right(resp.right().value());
838 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
839 if (validateComponentType.isRight()) {
840 return Either.right(validateComponentType.right().value());
843 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
844 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
845 if (validateComponentExists.isRight()) {
846 return Either.right(validateComponentExists.right().value());
848 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
849 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
850 if (validateCanWorkOnComponent.isRight()) {
851 return Either.right(validateCanWorkOnComponent.right().value());
854 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
855 if (lockComponent.isRight()) {
856 return Either.right(lockComponent.right().value());
860 * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
861 * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
862 * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
864 Either<ComponentInstance, ResponseFormat> resultOp = null;
866 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
867 if (resultOp.isRight()){
870 Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, componentInstanceId,
871 containerComponentType, resultOp);
872 if (deleteEither.isRight()){
879 * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
881 unlockComponent(resultOp, containerComponent);
885 public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
886 String componentInstanceId, ComponentTypeEnum containerComponentType,
887 Either<ComponentInstance, ResponseFormat> resultOp) {
888 if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
890 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstanceId);
891 if (!pathIDsToBeDeleted.isEmpty()) {
892 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
894 if(deleteForwardingPathsEither.isRight()) {
895 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
904 private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
906 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
907 if(storageStatus.isRight()) {
908 return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
910 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
911 Sets.newHashSet(pathIdsToDelete));
913 if(result.isRight()) {
914 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
916 return Either.left(result.left().value());
919 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
920 ComponentParametersView filter = new ComponentParametersView(true);
921 filter.setIgnoreForwardingPath(false);
922 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
923 .getToscaElement(containerComponentId, filter);
924 Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
925 List<String> pathIDsToBeDeleted = new ArrayList<>();
927 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
928 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
930 return pathIDsToBeDeleted;
933 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
934 String componentInstanceId){
935 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
936 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
937 elementDataDefinition.getToNode()
938 .equalsIgnoreCase(componentInstanceId));
942 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
944 Either<ComponentInstance, ResponseFormat> resultOp = null;
945 ComponentInstance deletedInstance = null;
946 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
948 if (deleteRes.isRight()) {
949 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
950 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
951 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
953 if (resultOp == null) {
954 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
955 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
956 resultOp = Either.left(deletedInstance);
958 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
959 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
960 for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
961 Map<String, String> members = currGroup.getMembers();
962 if (members != null && members.containsKey(deletedInstance.getName())) {
963 members.remove(deletedInstance.getName());
964 groupsToUpdate.add(currGroup);
967 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
968 if (updateGroupsRes.isRight()) {
969 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
970 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
971 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
974 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
975 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
976 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
977 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
978 if (deleteInputsRes != StorageOperationStatus.OK) {
979 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
980 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
987 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
988 ComponentInstance foundInstance = null;
989 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
990 if (instance.getUniqueId().equals(componentInstanceId)) {
991 foundInstance = instance;
992 containerComponent.getComponentInstances().remove(instance);
996 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
997 return foundInstance;
1000 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1001 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1002 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1006 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1007 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1010 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1011 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1014 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1015 boolean createNewTransaction) {
1017 Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
1018 if (resp.isRight()) {
1019 return Either.right(resp.right().value());
1022 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1024 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1025 if (validateComponentExists.isRight()) {
1026 return Either.right(validateComponentExists.right().value());
1028 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1030 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1031 if (validateCanWorkOnComponent.isRight()) {
1032 return Either.right(validateCanWorkOnComponent.right().value());
1035 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1037 if (lockComponent.isRight()) {
1038 return Either.right(lockComponent.right().value());
1044 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1050 unlockComponent(resultOp, containerComponent);
1054 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1056 log.debug("Try to create entry on graph");
1057 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1059 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1061 if (result.isLeft()) {
1062 log.debug("Enty on graph is created.");
1063 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1064 resultOp = Either.left(requirementCapabilityRelDef);
1068 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1069 String fromNameOrId = "";
1070 String toNameOrId = "";
1071 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1072 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1074 toNameOrId = requirementDef.getFromNode();
1075 fromNameOrId = requirementDef.getFromNode();
1076 if (fromResult.isLeft()) {
1077 fromNameOrId = fromResult.left().value().getName();
1079 if (toResult.isLeft()) {
1080 toNameOrId = toResult.left().value().getName();
1083 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1090 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1091 Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
1092 if (resp.isRight()) {
1093 return Either.right(resp.right().value());
1096 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1097 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1098 if (validateComponentExists.isRight()) {
1099 return Either.right(validateComponentExists.right().value());
1101 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1103 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1104 if (validateCanWorkOnComponent.isRight()) {
1105 return Either.right(validateCanWorkOnComponent.right().value());
1107 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1109 if (lockComponent.isRight()) {
1110 return Either.right(lockComponent.right().value());
1113 log.debug("Try to create entry on graph");
1114 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1115 if (result.isLeft()) {
1116 log.debug("Enty on graph is created.");
1117 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1118 resultOp = Either.left(requirementCapabilityRelDef);
1123 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1124 String fromNameOrId = "";
1125 String toNameOrId = "";
1126 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1127 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1129 toNameOrId = requirementDef.getFromNode();
1130 fromNameOrId = requirementDef.getFromNode();
1131 if (fromResult.isLeft()) {
1132 fromNameOrId = fromResult.left().value().getName();
1134 if (toResult.isLeft()) {
1135 toNameOrId = toResult.left().value().getName();
1139 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1143 unlockComponent(resultOp, containerComponent);
1147 * Allows to get relation contained in specified component according to received Id
1148 * @param componentId
1151 * @param componentTypeEnum
1154 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1156 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1158 org.openecomp.sdc.be.model.Component containerComponent = null;
1159 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1160 RequirementCapabilityRelDef foundRelation = null;
1162 Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "get relation by Id", false);
1163 if (validateUserRes.isRight()) {
1164 resultOp = Either.right(validateUserRes.right().value());
1166 if(resultOp == null){
1167 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1168 if (validateComponentExists.isRight()) {
1169 resultOp = Either.right(validateComponentExists.right().value());
1172 if(resultOp == null){
1173 containerComponent = validateComponentExists.left().value();
1174 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1175 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1176 if(foundRelation == null){
1177 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1178 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1179 resultOp = Either.right(responseFormat);
1182 if(resultOp == null){
1183 resultOp = setRelatedCapability(foundRelation, containerComponent);
1185 if(resultOp.isLeft()){
1186 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1188 } catch (Exception e) {
1189 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1190 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1195 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1196 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1197 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1198 return relationship;
1204 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1205 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1206 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1207 String instanceId = foundRelation.getFromNode();
1208 Optional<RequirementDefinition> foundRequirement;
1209 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1210 if(!instance.isPresent()){
1211 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1212 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1213 result = Either.right(responseFormat);
1216 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1217 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1218 if(foundRequirement.isPresent()){
1219 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1220 result = Either.left(foundRelation);
1225 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1226 if(getfulfilledRequirementRes.isRight()){
1227 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1228 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1229 result = Either.right(responseFormat);
1231 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1235 result = Either.left(foundRelation);
1240 private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1241 return req.getName().equals(relationshipInfo.getRequirement()) &&
1242 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1243 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1246 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1247 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1248 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1249 String instanceId = foundRelation.getToNode();
1250 Optional<CapabilityDefinition> foundCapability;
1251 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1252 if(!instance.isPresent()){
1253 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1254 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1255 result = Either.right(responseFormat);
1258 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1259 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1260 if(foundCapability.isPresent()){
1261 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1262 result = Either.left(foundRelation);
1267 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1268 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1269 if(getfulfilledRequirementRes.isRight()){
1270 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1271 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1272 result = Either.right(responseFormat);
1274 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1278 result = Either.left(foundRelation);
1283 private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1284 return cap.getName().equals(relationshipInfo.getCapability()) &&
1285 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1286 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1289 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1290 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1291 Either<ComponentInstanceProperty, ResponseFormat> result;
1292 if (eitherAttribute.isLeft()) {
1293 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1294 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1296 result = Either.left(instanceAttribute);
1299 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1301 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1303 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1309 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1311 Either<ComponentInstanceProperty, ResponseFormat> result;
1313 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1314 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1315 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1317 if (!errorWrapper.isEmpty()) {
1318 result = Either.right(errorWrapper.getInnerElement());
1320 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1321 if (eitherAttribute.isLeft()) {
1322 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1323 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1324 result = Either.left(instanceAttribute);
1327 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1329 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1330 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1338 * Create Or Updates Attribute Instance
1340 * @param componentTypeEnum
1341 * @param componentId
1342 * @param resourceInstanceId
1347 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1348 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1349 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1351 validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
1352 if (errorWrapper.isEmpty()) {
1353 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1355 if (errorWrapper.isEmpty()) {
1356 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1358 if (errorWrapper.isEmpty()) {
1359 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1363 if (errorWrapper.isEmpty()) {
1364 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1366 result = createAttributeValue(attribute, resourceInstanceId);
1368 result = updateAttributeValue(attribute, resourceInstanceId);
1371 result = Either.right(errorWrapper.getInnerElement());
1377 if (result == null || result.isRight()) {
1378 titanDao.rollback();
1383 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1387 private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1388 return StringUtils.isNotEmpty(property.getValue())
1389 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1390 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1393 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
1394 return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property));
1397 // US833308 VLI in service - specific network_role property value logic
1398 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1399 for (ComponentInstanceProperty property: properties) {
1400 if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1401 ComponentParametersView componentParametersView = new ComponentParametersView();
1402 componentParametersView.disableAll();
1403 componentParametersView.setIgnoreComponentInstances(false);
1404 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1405 if (getServiceResult.isRight()) {
1406 return getServiceResult.right().value();
1408 Component service = getServiceResult.left().value();
1409 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1410 if (!getInstance.isPresent()) {
1411 return StorageOperationStatus.NOT_FOUND;
1413 String prefix = service.getSystemName() + ".";
1414 String value = property.getValue();
1415 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1416 property.setValue(prefix + value);
1420 return StorageOperationStatus.OK;
1423 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1425 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1427 /*-------------------------------Validations---------------------------------*/
1429 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Properties Values", false);
1430 if (resp.isRight()) {
1431 return Either.right(resp.right().value());
1434 if (componentTypeEnum == null) {
1435 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO);
1436 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1439 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1441 if (getResourceResult.isRight()) {
1442 log.debug("Failed to retrieve component, component id {}", componentId);
1443 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1446 Component containerComponent = getResourceResult.left().value();
1448 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1449 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1450 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1453 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1454 if (resourceInstanceStatus.isRight()) {
1455 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1458 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1459 // specific property value logic US833308
1460 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1461 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1462 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1466 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1467 if (lockStatus != StorageOperationStatus.OK) {
1468 log.debug("Failed to lock service {}", componentId);
1469 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1474 for (ComponentInstanceProperty property: properties) {
1475 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1476 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1477 responseFormat -> Either.right(responseFormat));
1480 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1481 if (updateContainerRes.isRight()) {
1482 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1483 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1486 resultOp = Either.left(properties);
1490 if (resultOp == null || resultOp.isRight()) {
1491 titanDao.rollback();
1496 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1500 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1501 String capabilityType, String capabilityName) {
1502 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1503 StringBuffer sb = new StringBuffer(componentInstanceUniqueId);
1504 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1505 String capKey = sb.toString();
1507 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1508 .orElse(Collections.emptyMap());
1509 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1510 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1511 if (cap.isPresent()) {
1512 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1513 if (capProperties != null) {
1514 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1515 StorageOperationStatus status;
1516 if (instanceProperty.isPresent()) {
1517 instanceProperty.get().setValue(newValue);
1518 List<String> path = new ArrayList<>();
1519 path.add(componentInstanceUniqueId);
1521 instanceProperty.get().setPath(path);
1522 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1523 if (status != StorageOperationStatus.OK) {
1524 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1525 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1528 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1534 return componentsUtils.getResponseFormat(ActionStatus.OK);
1537 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1538 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1539 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1540 StorageOperationStatus status;
1541 instanceProperty.get().setValue(newValue);
1542 if (instanceProperty.isPresent()) {
1543 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1545 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1547 if (status != StorageOperationStatus.OK) {
1548 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1549 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1551 List<String> path = new ArrayList<>();
1552 path.add(foundResourceInstance.getUniqueId());
1553 property.setPath(path);
1555 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1556 return componentsUtils.getResponseFormat(ActionStatus.OK);
1559 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1560 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1561 if (allDataTypesEither.isRight()) {
1562 TitanOperationStatus status = allDataTypesEither.right().value();
1563 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1564 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1566 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1567 String innerType = null;
1568 String propertyType = property.getType();
1569 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1570 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1572 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1573 SchemaDefinition def = property.getSchema();
1575 log.debug("Schema doesn't exists for property of type {}", type);
1576 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1578 PropertyDataDefinition propDef = def.getProperty();
1579 if (propDef == null) {
1580 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1581 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1583 innerType = propDef.getType();
1585 // Specific Update Logic
1586 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1587 String newValue = property.getValue();
1588 if (isValid.isRight()) {
1589 Boolean res = isValid.right().value();
1591 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1594 Object object = isValid.left().value();
1595 if (object != null) {
1596 newValue = object.toString();
1600 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1601 if (pair.getRight() != null && pair.getRight() == false) {
1602 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1603 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1606 return Either.left(newValue);
1609 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1610 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1611 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1612 StorageOperationStatus status;
1613 if (instanceProperty.isPresent()) {
1614 instanceProperty.get().setValue(input.getValue());
1615 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1617 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1619 if (status != StorageOperationStatus.OK) {
1620 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1621 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1623 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1624 return componentsUtils.getResponseFormat(ActionStatus.OK);
1627 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1629 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1631 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1632 if (resp.isRight()) {
1633 return Either.right(resp.right().value());
1636 if (componentTypeEnum == null) {
1637 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1638 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1641 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1643 if (getResourceResult.isRight()) {
1644 log.debug("Failed to retrieve component, component id {}", componentId);
1645 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1648 Component containerComponent = getResourceResult.left().value();
1650 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1651 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1652 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1655 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1656 if (resourceInstanceStatus.isRight()) {
1657 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1661 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1664 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1665 if (lockStatus != StorageOperationStatus.OK) {
1666 log.debug("Failed to lock service {}", componentId);
1667 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1671 for (ComponentInstanceInput input: inputs) {
1672 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1673 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1674 responseFormat -> Either.right(responseFormat));
1677 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1679 if (updateContainerRes.isRight()) {
1680 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1681 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1684 resultOp = Either.left(inputs);
1688 if (resultOp == null || resultOp.isRight()) {
1689 titanDao.rollback();
1694 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1699 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1702 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1704 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
1705 if (resp.isRight()) {
1706 return Either.right(resp.right().value());
1709 if (componentTypeEnum == null) {
1710 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1711 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1715 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1716 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1717 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1721 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1722 if (lockStatus != StorageOperationStatus.OK) {
1723 log.debug("Failed to lock service {}", componentId);
1724 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1728 String propertyValueUid = property.getValueUniqueUid();
1730 if (propertyValueUid == null) {
1732 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1734 if (counterRes.isRight()) {
1735 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1736 StorageOperationStatus status = counterRes.right().value();
1737 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1738 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1740 Integer index = counterRes.left().value();
1741 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1743 if (result.isLeft()) {
1744 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1745 ComponentInstanceProperty instanceProperty = result.left().value();
1747 resultOp = Either.left(instanceProperty);
1750 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1752 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1754 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1758 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1760 if (result.isLeft()) {
1761 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1762 ComponentInstanceProperty instanceProperty = result.left().value();
1764 resultOp = Either.left(instanceProperty);
1767 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1769 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1771 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1774 if (resultOp.isLeft()) {
1775 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1776 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1777 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1779 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1786 if (resultOp == null || resultOp.isRight()) {
1787 titanDao.rollback();
1792 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1797 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
1799 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
1801 Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
1802 if (resp.isRight()) {
1803 return Either.right(resp.right().value());
1806 if (componentTypeEnum == null) {
1807 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
1808 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1812 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1813 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1814 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1818 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1819 if (lockStatus != StorageOperationStatus.OK) {
1820 log.debug("Failed to lock service {}", componentId);
1821 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1825 String propertyValueUid = inputProperty.getValueUniqueUid();
1826 if (propertyValueUid == null) {
1828 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
1830 if (counterRes.isRight()) {
1831 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
1832 StorageOperationStatus status = counterRes.right().value();
1833 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1834 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1836 Integer index = counterRes.left().value();
1837 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
1839 if (result.isLeft()) {
1840 log.debug("Property value was added to resource instance {}", resourceInstanceId);
1841 ComponentInstanceInput instanceProperty = result.left().value();
1843 resultOp = Either.left(instanceProperty);
1847 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
1849 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1851 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1857 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
1859 if (result.isLeft()) {
1860 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
1861 ComponentInstanceInput instanceProperty = result.left().value();
1863 resultOp = Either.left(instanceProperty);
1867 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
1869 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1871 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1878 if (resultOp == null || resultOp.isRight()) {
1879 titanDao.rollback();
1884 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1889 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
1891 Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
1892 if (resp.isRight()) {
1893 return Either.right(resp.right().value());
1896 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1898 if (componentTypeEnum == null) {
1899 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
1900 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1904 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
1905 log.info("Restricted operation for user {} on service {}", userId, serviceId);
1906 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1910 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
1911 if (lockStatus != StorageOperationStatus.OK) {
1912 log.debug("Failed to lock service {}", serviceId);
1913 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1917 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
1919 if (result.isLeft()) {
1920 log.debug("Property value {} was removed from graph.", propertyValueId);
1921 ComponentInstanceProperty instanceProperty = result.left().value();
1923 resultOp = Either.left(instanceProperty);
1927 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
1929 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1931 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1937 if (resultOp == null || resultOp.isRight()) {
1938 titanDao.rollback();
1943 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
1948 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1950 Either<Component, ResponseFormat> eitherResponse = null;
1951 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
1952 Component component;
1953 ResponseFormat errorResponse;
1954 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
1955 if (getComponentRes.isRight()) {
1956 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
1957 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
1958 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
1959 eitherResponse = Either.right(errorResponse);
1961 if (eitherResponse == null) {
1962 component = getComponentRes.left().value();
1963 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
1964 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
1965 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
1966 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
1967 eitherResponse = Either.right(errorResponse);
1970 if (eitherResponse == null) {
1971 eitherResponse = Either.left(getComponentRes.left().value());
1973 return eitherResponse;
1976 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
1977 String containerComponentId,
1978 String componentInstanceId,
1979 ComponentInstance newComponentInstance) {
1980 Either<Set<String>, ResponseFormat> resultOp;
1981 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
1982 if (validateComponentType.isRight()) {
1983 return Either.right(validateComponentType.right().value());
1985 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
1986 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
1989 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
1990 validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
1991 if (validateComponentExists.isRight()) {
1992 return Either.right(validateComponentExists.right().value());
1994 Component containerComponent = validateComponentExists.left().value();
1996 //Fetch current component instance
1997 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
1998 getResourceInstanceById(containerComponent, componentInstanceId);
1999 if (eitherResourceInstance.isRight()) {
2000 resultOp = Either.right(componentsUtils.getResponseFormat(
2001 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2004 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2006 //Check whether new componentInstance exists
2007 String resourceId = newComponentInstance.getComponentUid();
2008 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2009 if (componentExistsRes.isRight()) {
2010 log.debug("Failed to find resource ", resourceId);
2011 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2012 (componentExistsRes.right().value()), resourceId));
2014 } else if (!componentExistsRes.left().value()) {
2015 log.debug("The resource {} not found ", resourceId);
2016 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2020 //Fetch component using new component instance uid
2021 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2022 if (eitherResourceName.isRight()) {
2023 resultOp = Either.right(eitherResourceName.right().value());
2026 Component updatedContainerComponent=eitherResourceName.left().value();
2027 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2028 currentResourceInstance, updatedContainerComponent);
2029 resultOp=Either.left(toDeleteForwardingPaths);
2034 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2035 Component updatedContainerComponent) {
2036 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2037 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2039 Service service = (Service) containerComponent;
2040 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2042 return forwardingPathUtils.
2043 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2046 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2047 ComponentParametersView componentParametersView = new ComponentParametersView();
2048 componentParametersView.setIgnoreCapabiltyProperties(false);
2049 componentParametersView.setIgnoreForwardingPath(false);
2050 return componentParametersView;
2053 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2055 Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
2056 if (resp.isRight()) {
2057 return Either.right(resp.right().value());
2060 User user = resp.left().value();
2061 Either<ComponentInstance, ResponseFormat> resultOp = null;
2063 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2064 if (validateComponentType.isRight()) {
2065 return Either.right(validateComponentType.right().value());
2068 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2069 ComponentParametersView componentParametersView = new ComponentParametersView();
2070 componentParametersView.setIgnoreCapabiltyProperties(false);
2071 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2072 if (validateComponentExists.isRight()) {
2073 return Either.right(validateComponentExists.right().value());
2075 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2077 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2078 if (validateCanWorkOnComponent.isRight()) {
2079 return Either.right(validateCanWorkOnComponent.right().value());
2082 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2083 if (resourceInstanceStatus.isRight()) {
2084 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2088 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2090 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2091 if (lockComponent.isRight()) {
2092 return Either.right(lockComponent.right().value());
2098 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2099 resultOp = Either.left(currentResourceInstance);
2103 String resourceId = newComponentInstance.getComponentUid();
2107 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2108 if (componentExistsRes.isRight()) {
2109 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2110 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2112 } else if (!componentExistsRes.left().value()) {
2113 log.debug("The resource {} not found ", resourceId);
2114 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2118 Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2120 if (eitherOriginComponent.isRight()) {
2121 resultOp = Either.right(eitherOriginComponent.right().value());
2124 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2125 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2126 if (resultOp.isRight()) {
2127 log.debug("failed to delete resource instance {}", resourceId);
2130 ComponentInstance resResourceInfo = resultOp.left().value();
2131 Component origComponent = null;
2132 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2133 if (originType == OriginTypeEnum.ServiceProxy) {
2134 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2135 if (serviceProxyOrigin.isRight()) {
2136 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2137 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2139 origComponent = serviceProxyOrigin.left().value();
2141 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2143 if (fillProxyRes != StorageOperationStatus.OK) {
2144 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2145 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2148 newComponentInstance.setOriginType(originType);
2152 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2154 if (eitherResourceName.isRight()) {
2155 resultOp = Either.right(eitherResourceName.right().value());
2159 origComponent = eitherResourceName.left().value();
2161 newComponentInstance.setName(resResourceInfo.getName());
2164 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2165 newComponentInstance.setPosX(resResourceInfo.getPosX());
2166 newComponentInstance.setPosY(resResourceInfo.getPosY());
2167 newComponentInstance.setDescription(resResourceInfo.getDescription());
2169 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2171 if (resultOp.isRight()) {
2172 log.debug("failed to create resource instance {}", resourceId);
2176 ComponentInstance updatedComponentInstance = resultOp.left().value();
2177 if (resultOp.isRight()) {
2178 log.debug("failed to create resource instance {}", resourceId);
2182 Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2183 if (mergeStatusEither.isRight()) {
2184 return Either.right(mergeStatusEither.right().value());
2187 ActionStatus postChangeVersionResult = postChangeVersionOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2188 if (postChangeVersionResult != ActionStatus.OK) {
2189 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2192 ComponentParametersView filter = new ComponentParametersView(true);
2193 filter.setIgnoreComponentInstances(false);
2194 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2195 if (updatedComponentRes.isRight()) {
2196 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2197 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2198 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2199 log.debug("Component with id {} was not found", containerComponentId);
2200 return Either.right(responseFormat);
2202 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2203 if (resourceInstanceStatus.isRight()) {
2204 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2207 resultOp = Either.left(resourceInstanceStatus.left().value());
2211 unlockComponent(resultOp, containerComponent);
2216 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2217 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2218 Component containerComponent = null;
2220 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2222 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2223 if (validateUserExists.isRight()) {
2224 resultOp = Either.right(validateUserExists.right().value());
2228 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2229 if (validateComponentType.isRight()) {
2230 resultOp = Either.right(validateComponentType.right().value());
2234 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2235 if (validateContainerComponentExists.isRight()) {
2236 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2239 containerComponent = validateContainerComponentExists.left().value();
2241 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2242 if (resourceInstanceStatus.isRight()) {
2243 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2247 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2248 if (CollectionUtils.isEmpty(instanceProperties)) {
2249 instanceProperties = new ArrayList<>();
2251 resultOp = Either.left(instanceProperties);
2254 unlockComponent(resultOp, containerComponent);
2258 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2259 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2261 if (counterRes.isRight()) {
2262 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2263 StorageOperationStatus status = counterRes.right().value();
2264 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2265 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2267 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2273 * updates componentInstance modificationTime
2275 * @param componentInstance
2276 * @param componentInstanceType
2277 * @param modificationTime
2278 * @param inTransaction
2281 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2282 Either<ComponentInstanceData, ResponseFormat> result;
2283 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2285 if (updateComponentInstanceRes.isRight()) {
2286 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2287 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2289 result = Either.left(updateComponentInstanceRes.left().value());
2294 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
2295 // TODO Add implementation
2296 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2300 public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
2301 // TODO Add implementation
2302 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2306 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
2307 // TODO Add implementation
2308 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2312 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2313 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2316 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2318 Either<ComponentInstance, StorageOperationStatus> result = null;
2319 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2320 Optional<ComponentInstance> foundInstance = null;
2321 if (CollectionUtils.isEmpty(instances)) {
2322 result = Either.right(StorageOperationStatus.NOT_FOUND);
2324 if (result == null) {
2325 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2326 if (!foundInstance.isPresent()) {
2327 result = Either.right(StorageOperationStatus.NOT_FOUND);
2330 if (result == null) {
2331 result = Either.left(foundInstance.get());
2336 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2338 Long creationDate = origInstanceForUpdate.getCreationTime();
2340 Long modificationTime = System.currentTimeMillis();
2341 resourceInstanceForUpdate.setCreationTime(creationDate);
2342 resourceInstanceForUpdate.setModificationTime(modificationTime);
2344 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2346 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2347 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2350 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2352 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2353 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2355 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2356 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2358 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2359 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2361 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2362 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2364 if (resourceInstanceForUpdate.getOriginType() == null) {
2365 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2367 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2368 resourceInstanceForUpdate.setIsProxy(true);
2369 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2370 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2372 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2373 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2375 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2376 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2378 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2379 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2381 return resourceInstanceForUpdate;
2384 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2385 * @param containerComponentType
2386 * @param containerComponentId
2387 * @param componentInstanceUniqueId
2388 * @param capabilityType
2389 * @param capabilityName
2394 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2396 Component containerComponent = null;
2398 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2400 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false);
2401 if (validateUserExists.isRight()) {
2402 resultOp = Either.right(validateUserExists.right().value());
2404 if(resultOp == null){
2405 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2406 if (validateComponentType.isRight()) {
2407 resultOp = Either.right(validateComponentType.right().value());
2410 if(resultOp == null){
2411 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2412 if (validateContainerComponentExists.isRight()) {
2413 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2415 containerComponent = validateContainerComponentExists.left().value();
2418 if(resultOp == null){
2419 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2420 if (resourceInstanceStatus.isRight()) {
2421 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2423 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2428 unlockComponent(resultOp, containerComponent);
2432 private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2433 Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2434 CapabilityDefinition foundCapability;
2435 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2436 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2437 if (capabilitiesPerType != null) {
2438 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2439 if (capabilityOpt.isPresent()) {
2440 foundCapability = capabilityOpt.get();
2441 result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2445 if (result == null) {
2446 result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2451 private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2452 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2454 Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2455 if(getComponentInstanceCapabilityProperties.isRight()){
2456 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2458 resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
2460 } catch(Exception e){
2461 log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2462 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2467 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2468 String capabilityType, String capabilityName, String ownerId) {
2469 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2470 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2471 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2472 String capKey = sb.toString();
2474 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2475 .orElse(Collections.emptyMap());
2476 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2477 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2478 if (cap.isPresent()) {
2479 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2480 if (capProperties != null) {
2481 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2482 StorageOperationStatus status;
2483 if (instanceProperty.isPresent()) {
2484 instanceProperty.get().setValue(newValue);
2485 List<String> path = new ArrayList<>();
2486 path.add(componentInstanceUniqueId);
2488 instanceProperty.get().setPath(path);
2489 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2490 if (status != StorageOperationStatus.OK) {
2491 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2492 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2495 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2499 return componentsUtils.getResponseFormat(ActionStatus.OK);
2502 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2503 List<ComponentInstanceProperty> properties, String userId) {
2504 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2506 Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
2507 if (resp.isRight()) {
2508 return Either.right(resp.right().value());
2511 if (componentTypeEnum == null) {
2512 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2513 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2515 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2517 if (getResourceResult.isRight()) {
2518 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2519 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2521 Component containerComponent = getResourceResult.left().value();
2523 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2524 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2525 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2527 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2528 if (resourceInstanceStatus.isRight()) {
2529 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2531 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2533 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2534 if (lockStatus != StorageOperationStatus.OK) {
2535 log.debug("Failed to lock component {}", containerComponentId);
2536 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2539 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2540 if (allDataTypes.isRight()) {
2541 TitanOperationStatus status = allDataTypes.right().value();
2542 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2543 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2547 for (ComponentInstanceProperty property : properties) {
2548 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2549 newPropertyValueEither.bimap(updatedValue ->
2550 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2551 responseFormat -> Either.right(responseFormat));
2553 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2555 if (updateContainerRes.isRight()) {
2556 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2557 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2560 resultOp = Either.left(properties);
2564 if (resultOp == null || resultOp.isRight()) {
2565 titanDao.rollback();
2570 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2574 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2575 List<ComponentInstanceProperty> properties, String userId) {
2576 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2578 Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
2579 if (resp.isRight()) {
2580 return Either.right(resp.right().value());
2583 if (componentTypeEnum == null) {
2584 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
2585 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2587 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2589 if (getResourceResult.isRight()) {
2590 log.debug("Failed to retrieve component, component id {}", containerComponentId);
2591 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2593 Component containerComponent = getResourceResult.left().value();
2595 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2596 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2597 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2599 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2600 if (resourceInstanceStatus.isRight()) {
2601 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2603 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2605 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2606 if (lockStatus != StorageOperationStatus.OK) {
2607 log.debug("Failed to lock component {}", containerComponentId);
2608 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2612 for (ComponentInstanceProperty property : properties) {
2613 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2614 newPropertyValueEither.bimap(updatedValue ->
2615 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2616 responseFormat -> Either.right(responseFormat));
2618 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2620 if (updateContainerRes.isRight()) {
2621 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2622 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2625 resultOp = Either.left(properties);
2629 if (resultOp == null || resultOp.isRight()) {
2630 titanDao.rollback();
2635 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());