2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.collect.Sets;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
30 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtils;
31 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
32 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
33 import org.openecomp.sdc.be.components.utils.ProxyServicePropertiesUtils;
34 import org.openecomp.sdc.be.components.validation.ComponentValidations;
35 import org.openecomp.sdc.be.config.BeEcompErrorManager;
36 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
37 import org.openecomp.sdc.be.dao.api.ActionStatus;
38 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
39 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
40 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
41 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
42 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
43 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
44 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
45 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
46 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
51 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
52 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
53 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
54 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
55 import org.openecomp.sdc.be.model.Component;
56 import org.openecomp.sdc.be.model.ComponentParametersView;
57 import org.openecomp.sdc.be.model.CapabilityDefinition;
58 import org.openecomp.sdc.be.model.InterfaceDefinition;
59 import org.openecomp.sdc.be.model.RequirementDefinition;
60 import org.openecomp.sdc.be.model.Resource;
61 import org.openecomp.sdc.be.model.Service;
62 import org.openecomp.sdc.be.model.User;
63 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
64 import org.openecomp.sdc.be.model.LifecycleStateEnum;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.DataTypeDefinition;
67 import org.openecomp.sdc.be.model.PropertyDefinition;
68 import org.openecomp.sdc.be.model.GroupDefinition;
69 import org.openecomp.sdc.be.model.InputDefinition;
70 import org.openecomp.sdc.be.model.RelationshipInfo;
71 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
72 import org.openecomp.sdc.be.model.ComponentInstance;
73 import org.openecomp.sdc.be.model.ComponentInstanceInput;
74 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
75 import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
76 import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
77 import org.openecomp.sdc.be.model.jsontitan.operations.NodeFilterOperation;
78 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
79 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
80 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
81 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
82 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
83 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
84 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
85 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
86 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
87 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
88 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
89 import org.openecomp.sdc.common.api.Constants;
90 import org.openecomp.sdc.common.datastructure.Wrapper;
91 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
92 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
93 import org.openecomp.sdc.common.log.wrappers.Logger;
94 import org.openecomp.sdc.common.util.ValidationUtils;
95 import org.openecomp.sdc.exception.ResponseFormat;
96 import org.springframework.beans.factory.annotation.Autowired;
98 import java.util.Arrays;
99 import java.util.ArrayList;
100 import java.util.Collection;
101 import java.util.Collections;
102 import java.util.HashMap;
103 import java.util.Iterator;
104 import java.util.List;
105 import java.util.Map;
106 import java.util.Map.Entry;
107 import java.util.Objects;
108 import java.util.Optional;
109 import java.util.Set;
110 import java.util.UUID;
111 import java.util.function.BiConsumer;
112 import java.util.stream.Collectors;
114 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
116 @org.springframework.stereotype.Component
117 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
119 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
120 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
121 public static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
122 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
123 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
124 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
125 public static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
126 public static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
127 public static final String INVALID_COMPONENT_TYPE = "invalid component type";
128 public static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
129 public static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
130 public static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
131 public static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
132 public static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
135 private IComponentInstanceOperation componentInstanceOperation;
138 private ArtifactsBusinessLogic artifactBusinessLogic;
141 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
144 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
147 private ForwardingPathOperation forwardingPathOperation;
150 private NodeFilterOperation serviceFilterOperation;
152 public ComponentInstanceBusinessLogic() {
155 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
156 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
157 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
160 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
161 List<ComponentInstanceProperty> resList = new ArrayList<>();
162 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
163 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
164 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
166 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
168 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
170 ciName = ciOp.get().getName();
171 if (ciPropList != null && !ciPropList.isEmpty()) {
172 for(ComponentInstanceProperty prop: ciPropList){
173 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
174 if(inputsValues != null && !inputsValues.isEmpty()){
175 for(GetInputValueDataDefinition inputData: inputsValues){
176 if(isGetInputValueForInput(inputData, inputId)){
177 prop.setComponentInstanceId(s);
178 prop.setComponentInstanceName(ciName);
193 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
194 List<ComponentInstanceInput> resList = new ArrayList<>();
195 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
196 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
197 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
199 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
201 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
203 ciName = ciOp.get().getName();
204 if (ciPropList != null && !ciPropList.isEmpty()) {
205 for(ComponentInstanceInput prop: ciPropList){
206 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
207 if(inputsValues != null && !inputsValues.isEmpty()){
208 for(GetInputValueDataDefinition inputData: inputsValues){
209 if(isGetInputValueForInput(inputData, inputId)){
210 prop.setComponentInstanceId(s);
211 prop.setComponentInstanceName(ciName);
226 public Either<ComponentInstance, ResponseFormat> createComponentInstance(
227 String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
229 Component origComponent = null;
230 Either<ComponentInstance, ResponseFormat> resultOp = null;
232 org.openecomp.sdc.be.model.Component containerComponent = null;
233 ComponentTypeEnum containerComponentType;
236 user = validateUserExists(userId, "create Component Instance", inTransaction);
238 Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
239 if (validateValidJson.isRight()) {
240 return Either.right(validateValidJson.right().value());
243 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
244 if (validateComponentType.isRight()) {
245 return Either.right(validateComponentType.right().value());
247 containerComponentType = validateComponentType.left().value();
250 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
251 if (validateComponentExists.isRight()) {
252 return Either.right(validateComponentExists.right().value());
254 containerComponent = validateComponentExists.left().value();
257 if (ModelConverter.isAtomicComponent(containerComponent)) {
258 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
259 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
262 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
263 if (validateCanWorkOnComponent.isRight()) {
264 return Either.right(validateCanWorkOnComponent.right().value());
267 if (resourceInstance != null && containerComponentType != null) {
268 OriginTypeEnum originType = resourceInstance.getOriginType();
269 if (originType == OriginTypeEnum.ServiceProxy) {
270 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
271 if (serviceProxyOrigin.isRight()) {
272 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
273 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
275 origComponent = serviceProxyOrigin.left().value();
277 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
278 if (fillProxyRes != StorageOperationStatus.OK) {
279 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
280 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
285 Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
287 if (getOriginComponentRes.isRight()) {
288 return Either.right(getOriginComponentRes.right().value());
290 origComponent = getOriginComponentRes.left().value();
295 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
296 if (lockComponent.isRight()) {
297 return Either.right(lockComponent.right().value());
300 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
301 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
306 unlockComponent(resultOp, containerComponent);
310 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
311 resourceInstance.setIsProxy(true);
312 ComponentParametersView filter = new ComponentParametersView(true);
313 filter.setIgnoreCapabilities(false);
314 filter.setIgnoreCapabiltyProperties(false);
315 filter.setIgnoreComponentInstances(false);
316 filter.setIgnoreRequirements(false);
317 filter.setIgnoreInterfaces(false);
318 filter.setIgnoreProperties(false);
319 filter.setIgnoreInputs(false);
320 Either<Component, StorageOperationStatus> serviceRes =
321 toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
322 if (serviceRes.isRight()) {
323 return serviceRes.right().value();
325 Component service = serviceRes.left().value();
326 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
327 resourceInstance.setCapabilities(capabilities);
328 Map<String, List<RequirementDefinition>> req = service.getRequirements();
329 resourceInstance.setRequirements(req);
331 Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
332 if(MapUtils.isNotEmpty(serviceInterfaces)) {
333 serviceInterfaces.forEach(resourceInstance::addInterface);
337 resourceInstance.setProperties(ProxyServicePropertiesUtils.getProperties(service));
339 List<InputDefinition> serviceInputs = service.getInputs();
340 resourceInstance.setInputs(serviceInputs);
342 String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
343 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
344 int lastIndexOf = toscaResourceName.lastIndexOf('.');
345 if (lastIndexOf != -1) {
346 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
347 resourceInstance.setToscaComponentName(proxyToscaName);
349 resourceInstance.setName(name);
350 resourceInstance.setIsProxy(true);
351 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
352 resourceInstance.setSourceModelName(service.getName());
353 resourceInstance.setSourceModelUuid(service.getUUID());
354 resourceInstance.setSourceModelUid(service.getUniqueId());
355 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
356 resourceInstance.setDescription("A Proxy for Service " + service.getName());
357 resourceInstance.setComponentVersion(service.getVersion());
359 return StorageOperationStatus.OK;
362 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
364 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
365 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
366 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
368 User user = validateUserExists(userId, "create And Associate RI To RI", false);
370 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
371 if (validateComponentType.isRight()) {
372 return Either.right(validateComponentType.right().value());
375 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
377 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
378 if (validateComponentExists.isRight()) {
379 return Either.right(validateComponentExists.right().value());
381 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
383 if (ModelConverter.isAtomicComponent(containerComponent)) {
384 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
385 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
388 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
389 if (validateCanWorkOnComponent.isRight()) {
390 return Either.right(validateCanWorkOnComponent.right().value());
393 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
394 if (lockComponent.isRight()) {
395 return Either.right(lockComponent.right().value());
399 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
400 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
402 if (eitherResourceName.isRight()) {
403 resultOp = Either.right(eitherResourceName.right().value());
406 Component origComponent = eitherResourceName.left().value();
408 Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
409 if (result.isRight()) {
410 log.debug("Failed to create resource instance {}", containerComponentId);
411 resultOp = Either.right(result.right().value());
416 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
417 ComponentInstance resResourceInfo = result.left().value();
418 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
419 associationInfo.setFromNode(resResourceInfo.getUniqueId());
421 associationInfo.setToNode(resResourceInfo.getUniqueId());
424 RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
425 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
426 if (resultReqCapDef.isLeft()) {
427 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
428 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
429 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
430 resultOp = Either.left(resInfo);
434 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
435 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
440 unlockComponent(resultOp, containerComponent);
444 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
445 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
448 private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
449 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
452 private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
453 Either<Component, ResponseFormat> eitherResponse;
454 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
455 if (eitherComponent.isRight()) {
456 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
457 eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
459 eitherResponse = Either.left(eitherComponent.left().value());
461 return eitherResponse;
464 private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
465 Either<ComponentInstance, ResponseFormat> resultOp;
467 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
469 if (result.isRight()) {
470 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
471 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
475 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
476 Component updatedComponent = result.left().value().getLeft();
477 Map<String, String> existingEnvVersions = new HashMap<>();
478 // TODO existingEnvVersions ??
479 Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
480 if (addComponentInstanceArtifacts.isRight()) {
481 log.debug("Failed to create component instance {}", componentInstance.getName());
482 resultOp = Either.right(addComponentInstanceArtifacts.right().value());
486 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
487 if (!updatedInstanceOptional.isPresent()) {
488 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
489 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
492 resultOp = Either.left(updatedInstanceOptional.get());
496 public boolean isCloudSpecificArtifact(String artifact) {
497 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
498 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
499 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(str -> artifact.contains(str))) {
511 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
512 * @param containerComponent
513 * @param componentInstance
514 * @param originComponent
516 * @param existingEnvVersions
519 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) {
521 log.debug("add artifacts to resource instance");
522 List<GroupDefinition> filteredGroups = null;
523 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
524 if (!ActionStatus.OK.equals(status)) {
525 ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
526 return Either.right(resultOp);
528 StorageOperationStatus artStatus;
529 // generate heat_env if necessary
530 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
531 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
533 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
534 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
536 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
537 String type = artifact.getArtifactType();
538 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
539 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
541 if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType()))) {
544 if (artifact.checkEsIdExist()) {
545 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
546 componentInstance.getName(), user, containerComponent, existingEnvVersions);
547 if (createHeatEnvPlaceHolder.isRight()) {
548 return Either.right(createHeatEnvPlaceHolder.right().value());
550 ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
552 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
554 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
555 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
557 if (CollectionUtils.isNotEmpty(filteredGroups)) {
558 for (GroupDefinition groupInstance : filteredGroups) {
559 Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
560 if (op.isPresent()) {
561 List<ArtifactDefinition> artifactsUid;
562 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
563 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
565 artifactsUid = new ArrayList<>();
567 artifactsUid.add(artifactDefinition);
568 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
572 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
573 groupInstance.getArtifacts().add(artifactDefinition.getGeneratedFromId());
579 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
580 if (artStatus != StorageOperationStatus.OK) {
581 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
582 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
585 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
586 if (result != StorageOperationStatus.OK) {
587 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
588 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
590 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
593 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
594 if (artStatus != StorageOperationStatus.OK) {
595 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
596 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
599 componentInstance.setArtifacts(originComponent.getArtifacts());
600 return Either.left(ActionStatus.OK);
603 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
604 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
606 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
607 if (getResourceDeploymentArtifacts.isRight()) {
608 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
609 if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
610 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
611 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
614 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
617 if (!deploymentArtifacts.isEmpty()) {
618 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
619 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
620 if (!artifact.getValue().checkEsIdExist()) {
621 tempDeploymentArtifacts.remove(artifact.getKey());
625 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
628 return ActionStatus.OK;
631 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
632 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
635 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
636 boolean needLock, boolean createNewTransaction) {
638 validateUserExists(userId, "update Component Instance", inTransaction);
640 Either<ComponentInstance, ResponseFormat> resultOp = null;
642 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
643 if (validateComponentType.isRight()) {
644 return Either.right(validateComponentType.right().value());
647 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
649 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
650 if (validateComponentExists.isRight()) {
651 return Either.right(validateComponentExists.right().value());
653 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
655 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
656 if (validateCanWorkOnComponent.isRight()) {
657 return Either.right(validateCanWorkOnComponent.right().value());
659 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
660 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
661 if (validateParentStatus.isRight()) {
662 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
663 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
666 if (!validateParentStatus.left().value()) {
667 resultOp = Either.right(
668 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
673 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
674 if (lockComponent.isRight()) {
675 return Either.right(lockComponent.right().value());
680 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
682 if (eitherResourceName.isRight()) {
683 resultOp = Either.right(eitherResourceName.right().value());
686 Component origComponent = eitherResourceName.left().value();
688 resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
693 unlockComponent(resultOp, containerComponent);
697 // New Multiple Instance Update API
698 public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
700 Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
701 org.openecomp.sdc.be.model.Component containerComponent = null;
703 validateUserExists(userId, "update Component Instance", true);
705 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
706 if (validateComponentType.isRight()) {
707 return Either.right(validateComponentType.right().value());
710 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
712 ComponentParametersView componentFilter = new ComponentParametersView();
713 componentFilter.disableAll();
714 componentFilter.setIgnoreUsers(false);
715 componentFilter.setIgnoreComponentInstances(false);
716 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
717 if (validateComponentExists.isRight()) {
718 return Either.right(validateComponentExists.right().value());
721 containerComponent = validateComponentExists.left().value();
723 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
724 if (validateCanWorkOnComponent.isRight()) {
725 return Either.right(validateCanWorkOnComponent.right().value());
728 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
730 for (ComponentInstance componentInstance : componentInstanceList) {
731 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
732 if (!validateParent) {
733 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
734 containerComponentId));
741 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
742 if (lockComponent.isRight()) {
743 return Either.right(lockComponent.right().value());
747 List<ComponentInstance> updatedList = new ArrayList<>();
748 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
749 List<ComponentInstance> listForUpdate = new ArrayList<>();
750 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
751 containerComponent.setComponentInstances(componentInstanceList);
753 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
754 while (iterator.hasNext()) {
755 ComponentInstance origInst = iterator.next();
756 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
757 if (op.isPresent()) {
758 ComponentInstance updatedCi = op.get();
759 updatedCi = buildComponentInstance(updatedCi, origInst);
761 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
763 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());
764 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
767 listForUpdate.add(updatedCi);
769 listForUpdate.add(origInst);
771 containerComponent.setComponentInstances(listForUpdate);
773 if (resultOp == null) {
774 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
775 if (updateStatus.isRight()) {
776 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
777 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
780 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
781 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
782 if (op.isPresent()) {
783 updatedList.add(updatedInstance);
789 resultOp = Either.left(updatedList);
794 unlockComponent(resultOp, containerComponent);
799 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
800 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
803 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
804 if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
805 return ComponentTypeEnum.SERVICE_INSTANCE;
807 return ComponentTypeEnum.RESOURCE_INSTANCE;
811 private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
812 ComponentInstance componentInstance) {
814 Either<ComponentInstance, ResponseFormat> resultOp = null;
815 Optional<ComponentInstance> componentInstanceOptional = null;
816 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
817 ComponentInstance oldComponentInstance = null;
818 boolean isNameChanged = false;
820 if (resultOp == null) {
821 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
822 if (!componentInstanceOptional.isPresent()) {
823 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
824 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
827 if (resultOp == null) {
828 oldComponentInstance = componentInstanceOptional.get();
829 String newInstanceName = componentInstance.getName();
830 if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
831 isNameChanged = true;
832 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
834 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);
835 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
837 if(!DirectivesUtils.isValid(componentInstance.getDirectives())) {
838 final String directivesStr =
839 componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
840 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
841 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
842 oldComponentInstance.getName(), newInstanceName ,
844 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.DIRECTIVES_INVALID_VALUE,
848 String newInstanceName = componentInstance.getName();
849 String oldInstanceName = null;
850 if (resultOp == null) {
851 oldComponentInstance = componentInstanceOptional.get();
852 newInstanceName = componentInstance.getName();
853 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
854 if (updateRes.isRight()) {
855 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
856 updateRes.right().value());
857 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
859 // region - Update instance Groups
861 Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
862 if (result.isRight())
863 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
864 if (containerComponent instanceof Service) {
865 Either<ComponentInstance, ResponseFormat> renameEither =
866 renameServiceFilter((Service) containerComponent, newInstanceName,
868 if (renameEither.isRight()) {
876 if (resultOp == null) {
877 String newInstanceId = updateRes.left().value().getRight();
878 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
880 if (!updatedInstanceOptional.isPresent()) {
881 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
882 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
884 resultOp = Either.left(updatedInstanceOptional.get());
888 if (resultOp == null) {
889 resultOp = Either.left(componentInstanceOptional.get());
895 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(Service containerComponent,
896 String newInstanceName, String oldInstanceName) {
898 Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
899 ServiceFilterUtils.getRenamedNodesFilter((Service) containerComponent,
900 oldInstanceName, newInstanceName);
901 for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){
902 Either<CINodeFilterDataDefinition, StorageOperationStatus>
903 renameEither = serviceFilterOperation.updateNodeFilter(
904 containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
905 if (renameEither.isRight()){
906 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
907 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
908 containerComponent.getName(), null));
912 return Either.left(null);
917 * The normalized old vf name
918 * @param newNormailzedPrefix-
919 * The normalized new vf name
920 * @param qualifiedGroupInstanceName-
921 * old Group Instance Name
923 // modify group names
924 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
925 if (qualifiedGroupInstanceName == null) {
926 log.info("CANNOT change group name ");
929 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
930 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
931 return qualifiedGroupInstanceName;
934 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
935 oldComponentInstance.setName(newComponentInstance.getName());
936 oldComponentInstance.setModificationTime(System.currentTimeMillis());
937 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
938 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
939 if (oldComponentInstance.getGroupInstances() != null)
940 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
941 return oldComponentInstance;
944 public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
946 validateUserExists(userId, "delete Component Instance", false);
948 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
949 if (validateComponentType.isRight()) {
950 return Either.right(validateComponentType.right().value());
953 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
954 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
955 if (validateComponentExists.isRight()) {
956 return Either.right(validateComponentExists.right().value());
958 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
959 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
960 if (validateCanWorkOnComponent.isRight()) {
961 return Either.right(validateCanWorkOnComponent.right().value());
964 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
965 if (lockComponent.isRight()) {
966 return Either.right(lockComponent.right().value());
969 Either<ComponentInstance, ResponseFormat> resultOp = null;
971 if (containerComponent instanceof Service) {
972 ComponentInstance componentInstance = containerComponent.getComponentInstanceById(componentInstanceId).get();
973 Either<String, StorageOperationStatus> deleteServiceFilterEither =
974 serviceFilterOperation.deleteNodeFilter((Service) containerComponent, componentInstanceId);
975 if (deleteServiceFilterEither.isRight()) {
976 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
977 containerComponentType);
979 return Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
981 resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent,
982 componentInstance, ComponentTypeEnum.SERVICE, userId);
983 if (resultOp.isRight()) {
988 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
989 if (resultOp.isRight()){
992 Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
993 containerComponentType, resultOp);
994 if (deleteEither.isRight()){
1000 unlockComponent(resultOp, containerComponent);
1004 public Either<ComponentInstance, ResponseFormat> deleteServiceFiltersRelatedTobeDeletedComponentInstance(
1005 Service service, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String userId) {
1006 if (containerComponentType.equals(ComponentTypeEnum.SERVICE)) {
1007 Set<String> serviceFiltersIDsToBeDeleted =
1008 getServiceFiltersRelatedToComponentInstance(service.getUniqueId(), componentInstance);
1009 if (!serviceFiltersIDsToBeDeleted.isEmpty()) {
1010 Set<String> ids = service.getComponentInstances().stream()
1011 .filter(ci -> serviceFiltersIDsToBeDeleted
1012 .contains(ci.getName()))
1013 .map(ComponentInstance::getUniqueId)
1014 .collect(Collectors.toSet());
1015 Either<Set<String>, StorageOperationStatus> deleteServiceFiltersEither =
1016 serviceFilterOperation.deleteNodeFilters(service, ids);
1017 if (deleteServiceFiltersEither.isRight()) {
1018 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFiltersEither.right().value(),
1019 containerComponentType);
1020 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1022 for (String id : ids) {
1023 final Optional<ComponentInstance> componentInstanceById = service.getComponentInstanceById(id);
1024 if (!componentInstanceById.isPresent()){
1025 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1027 ComponentInstance ci = componentInstanceById.get();
1028 List<String> directives = ci.getDirectives();
1029 directives.remove(DirectivesUtils.SELECTABLE);
1030 ci.setDirectives(directives);
1031 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
1032 updateComponentInstanceMetadata(ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUniqueId(),
1033 ci.getUniqueId(), userId, ci, true, false, false);
1034 if (componentInstanceResponseFormatEither.isRight()) {
1035 return componentInstanceResponseFormatEither;
1040 return Either.left(componentInstance);
1045 private Set<String> getServiceFiltersRelatedToComponentInstance(String containerComponentId,
1046 ComponentInstance componentInstance) {
1047 ComponentParametersView filter = new ComponentParametersView(true);
1048 filter.setIgnoreComponentInstances(false);
1049 Either<Service, StorageOperationStatus> serviceFilterOrigin =
1050 toscaOperationFacade.getToscaElement(containerComponentId, filter);
1051 final Service service = serviceFilterOrigin.left().value();
1052 final Set<String> nodesFiltersToBeDeleted = ServiceFilterUtils.getNodesFiltersToBeDeleted(service,
1054 return nodesFiltersToBeDeleted;
1058 public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
1059 Either<ComponentInstance, ResponseFormat> resultOp) {
1060 if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
1061 final ComponentInstance componentInstance = resultOp.left().value();
1062 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1063 if (!pathIDsToBeDeleted.isEmpty()) {
1064 Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
1065 pathIDsToBeDeleted);
1066 if(deleteForwardingPathsEither.isRight()) {
1067 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1076 private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
1078 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1079 if(storageStatus.isRight()) {
1080 return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
1082 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
1083 Sets.newHashSet(pathIdsToDelete));
1085 if(result.isRight()) {
1086 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
1088 return Either.left(result.left().value());
1091 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
1092 ComponentParametersView filter = new ComponentParametersView(true);
1093 filter.setIgnoreForwardingPath(false);
1094 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
1095 .getToscaElement(containerComponentId, filter);
1096 Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
1097 List<String> pathIDsToBeDeleted = new ArrayList<>();
1099 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
1100 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1102 return pathIDsToBeDeleted;
1105 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
1106 String componentInstanceId){
1107 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
1108 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
1109 elementDataDefinition.getToNode()
1110 .equalsIgnoreCase(componentInstanceId));
1114 private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
1116 Either<ComponentInstance, ResponseFormat> resultOp = null;
1117 ComponentInstance deletedInstance = null;
1118 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1120 if (deleteRes.isRight()) {
1121 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1122 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1123 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
1125 if (resultOp == null) {
1126 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1127 deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1128 resultOp = Either.left(deletedInstance);
1130 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
1131 List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
1132 for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
1133 Map<String, String> members = currGroup.getMembers();
1134 if (members != null && members.containsKey(deletedInstance.getName())) {
1135 members.remove(deletedInstance.getName());
1136 groupsToUpdate.add(currGroup);
1139 Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
1140 if (updateGroupsRes.isRight()) {
1141 log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
1142 ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
1143 resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
1146 if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1147 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1148 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1149 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1150 if (deleteInputsRes != StorageOperationStatus.OK) {
1151 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1152 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
1159 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1160 ComponentInstance foundInstance = null;
1161 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1162 if (instance.getUniqueId().equals(componentInstanceId)) {
1163 foundInstance = instance;
1164 containerComponent.getComponentInstances().remove(instance);
1168 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1169 return foundInstance;
1172 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1173 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1174 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1178 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1179 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1182 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1183 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
1186 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
1187 boolean createNewTransaction) {
1189 validateUserExists(userId, "associate Ri To RI", inTransaction);
1191 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1193 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1194 if (validateComponentExists.isRight()) {
1195 return Either.right(validateComponentExists.right().value());
1197 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1199 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1200 if (validateCanWorkOnComponent.isRight()) {
1201 return Either.right(validateCanWorkOnComponent.right().value());
1204 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1206 if (lockComponent.isRight()) {
1207 return Either.right(lockComponent.right().value());
1213 resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
1219 unlockComponent(resultOp, containerComponent);
1223 public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
1225 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1226 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1228 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
1230 if (result.isLeft()) {
1231 log.debug("Enty on graph is created.");
1232 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1233 resultOp = Either.left(requirementCapabilityRelDef);
1237 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1238 String fromNameOrId = "";
1239 String toNameOrId = "";
1240 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1241 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1243 toNameOrId = requirementDef.getFromNode();
1244 fromNameOrId = requirementDef.getFromNode();
1245 if (fromResult.isLeft()) {
1246 fromNameOrId = fromResult.left().value().getName();
1248 if (toResult.isLeft()) {
1249 toNameOrId = toResult.left().value().getName();
1252 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1260 * @param componentId
1262 * @param requirementDefList
1263 * @param componentTypeEnum
1266 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1269 List<RequirementCapabilityRelDef> requirementDefList,
1270 ComponentTypeEnum componentTypeEnum) {
1272 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1273 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1274 if (validateResponse.isRight()) {
1278 Component containerComponent = validateResponse.left().value();
1279 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1280 if (lockComponent.isRight()) {
1284 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1285 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = dissociateRIFromRI(
1286 componentId, requirementDef, containerComponent);
1288 if (actionResponse.isLeft()) {
1289 delOkResult.add(actionResponse.left().value());
1293 unlockComponent(validateResponse, containerComponent);
1298 public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1299 String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1300 Either<Component, ResponseFormat> validateResponse = validateDissociateRI(componentId, userId, componentTypeEnum);
1301 if(validateResponse.isRight())
1303 return Either.right(validateResponse.right().value());
1305 Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = null;
1306 Component containerComponent = validateResponse.left().value();
1307 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
1308 if (lockComponent.isRight()) {
1309 return Either.right(lockComponent.right().value());
1312 actionResponse = dissociateRIFromRI(
1313 componentId, requirementDef,containerComponent);
1315 unlockComponent(validateResponse, containerComponent);
1317 return actionResponse;
1320 private Either<Component, ResponseFormat> validateDissociateRI(
1321 String componentId, String userId, ComponentTypeEnum componentTypeEnum) {
1322 validateUserExists(userId, "dissociate RI From RI", false);
1325 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1326 if (validateComponentExists.isRight()) {
1327 return Either.right(validateComponentExists.right().value());
1329 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
1331 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
1332 if (validateCanWorkOnComponent.isRight()) {
1333 return Either.right(validateCanWorkOnComponent.right().value());
1335 return Either.left(containerComponent);
1338 private Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(
1339 String componentId, RequirementCapabilityRelDef requirementDef, Component containerComponent) {
1341 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1342 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1343 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(
1344 componentId, requirementDef);
1345 if (result.isLeft()) {
1346 log.debug("Enty on graph is created.");
1347 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1348 resultOp = Either.left(requirementCapabilityRelDef);
1353 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1354 String fromNameOrId = "";
1355 String toNameOrId = "";
1356 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(
1357 containerComponent, requirementDef.getFromNode());
1358 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(
1359 containerComponent, requirementDef.getToNode());
1361 toNameOrId = requirementDef.getFromNode();
1362 fromNameOrId = requirementDef.getFromNode();
1363 if (fromResult.isLeft()) {
1364 fromNameOrId = fromResult.left().value().getName();
1366 if (toResult.isLeft()) {
1367 toNameOrId = toResult.left().value().getName();
1371 .right(componentsUtils.getResponseFormat(
1372 componentsUtils.convertFromStorageResponseForResourceInstance(
1373 result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
1379 * Allows to get relation contained in specified component according to received Id
1380 * @param componentId
1383 * @param componentTypeEnum
1386 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1388 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1390 org.openecomp.sdc.be.model.Component containerComponent = null;
1391 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1392 RequirementCapabilityRelDef foundRelation = null;
1394 validateUserExists(userId, "get relation by Id", false);
1396 if(resultOp == null){
1397 validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
1398 if (validateComponentExists.isRight()) {
1399 resultOp = Either.right(validateComponentExists.right().value());
1402 if(resultOp == null){
1403 containerComponent = validateComponentExists.left().value();
1404 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1405 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1406 if(foundRelation == null){
1407 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1408 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1409 resultOp = Either.right(responseFormat);
1412 if(resultOp == null){
1413 resultOp = setRelatedCapability(foundRelation, containerComponent);
1415 if(resultOp.isLeft()){
1416 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1418 } catch (Exception e) {
1419 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1420 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1425 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1426 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1427 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1428 return relationship;
1434 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1435 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1436 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1437 String instanceId = foundRelation.getFromNode();
1438 Optional<RequirementDefinition> foundRequirement;
1439 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1440 if(!instance.isPresent()){
1441 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1442 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1443 result = Either.right(responseFormat);
1446 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1447 foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
1448 if(foundRequirement.isPresent()){
1449 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1450 result = Either.left(foundRelation);
1455 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
1456 if(getfulfilledRequirementRes.isRight()){
1457 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1458 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1459 result = Either.right(responseFormat);
1461 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1465 result = Either.left(foundRelation);
1470 private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1471 return req.getName().equals(relationshipInfo.getRequirement()) &&
1472 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1473 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1476 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1477 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1478 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1479 String instanceId = foundRelation.getToNode();
1480 Optional<CapabilityDefinition> foundCapability;
1481 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1482 if(!instance.isPresent()){
1483 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1484 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1485 result = Either.right(responseFormat);
1488 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1489 foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
1490 if(foundCapability.isPresent()){
1491 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1492 result = Either.left(foundRelation);
1497 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1498 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
1499 if(getfulfilledRequirementRes.isRight()){
1500 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1501 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1502 result = Either.right(responseFormat);
1504 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1508 result = Either.left(foundRelation);
1513 private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1514 return cap.getName().equals(relationshipInfo.getCapability()) &&
1515 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1516 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1519 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1520 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1521 Either<ComponentInstanceProperty, ResponseFormat> result;
1522 if (eitherAttribute.isLeft()) {
1523 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1524 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1526 result = Either.left(instanceAttribute);
1529 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1531 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1533 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1539 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1541 Either<ComponentInstanceProperty, ResponseFormat> result;
1543 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1544 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1545 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1547 if (!errorWrapper.isEmpty()) {
1548 result = Either.right(errorWrapper.getInnerElement());
1550 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1551 if (eitherAttribute.isLeft()) {
1552 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1553 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1554 result = Either.left(instanceAttribute);
1557 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1559 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1560 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1568 * Create Or Updates Attribute Instance
1570 * @param componentTypeEnum
1571 * @param componentId
1572 * @param resourceInstanceId
1577 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1578 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1579 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1581 validateUserExist(userId, "create Or Update Attribute Value");
1582 if (errorWrapper.isEmpty()) {
1583 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1585 if (errorWrapper.isEmpty()) {
1586 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1588 if (errorWrapper.isEmpty()) {
1589 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1593 if (errorWrapper.isEmpty()) {
1594 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1596 result = createAttributeValue(attribute, resourceInstanceId);
1598 result = updateAttributeValue(attribute, resourceInstanceId);
1601 result = Either.right(errorWrapper.getInnerElement());
1607 if (result == null || result.isRight()) {
1608 titanDao.rollback();
1613 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1617 private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
1618 return StringUtils.isNotEmpty(property.getValue())
1619 && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
1620 && ComponentTypeEnum.SERVICE == componentTypeEnum;
1623 // US833308 VLI in service - specific network_role property value logic
1624 private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
1625 for (ComponentInstanceProperty property: properties) {
1626 if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
1627 ComponentParametersView componentParametersView = new ComponentParametersView();
1628 componentParametersView.disableAll();
1629 componentParametersView.setIgnoreComponentInstances(false);
1630 Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
1631 if (getServiceResult.isRight()) {
1632 return getServiceResult.right().value();
1634 Component service = getServiceResult.left().value();
1635 Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
1636 if (!getInstance.isPresent()) {
1637 return StorageOperationStatus.NOT_FOUND;
1639 String prefix = service.getSystemName() + ".";
1640 String value = property.getValue();
1641 if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
1642 property.setValue(prefix + value);
1646 return StorageOperationStatus.OK;
1649 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1651 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1653 /*-------------------------------Validations---------------------------------*/
1655 validateUserExists(userId, "create Or Update Properties Values", false);
1657 if (componentTypeEnum == null) {
1658 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1659 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1662 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1664 if (getResourceResult.isRight()) {
1665 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1666 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1669 Component containerComponent = getResourceResult.left().value();
1671 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1672 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1673 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1676 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1677 if (resourceInstanceStatus.isRight()) {
1678 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1681 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1682 // specific property value logic US833308
1683 StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
1684 if (StorageOperationStatus.OK != fetchByIdsStatus) {
1685 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
1689 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1690 if (lockStatus != StorageOperationStatus.OK) {
1691 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1692 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1697 for (ComponentInstanceProperty property: properties) {
1698 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1699 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
1700 responseFormat -> Either.right(responseFormat));
1703 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1704 if (updateContainerRes.isRight()) {
1705 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1706 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1709 resultOp = Either.left(properties);
1713 if (resultOp == null || resultOp.isRight()) {
1714 titanDao.rollback();
1719 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1723 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1724 String capabilityType, String capabilityName) {
1725 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1726 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
1727 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
1728 String capKey = sb.toString();
1730 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
1731 .orElse(Collections.emptyMap());
1732 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
1733 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1734 if (cap.isPresent()) {
1735 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1736 if (capProperties != null) {
1737 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1738 StorageOperationStatus status;
1739 if (instanceProperty.isPresent()) {
1740 instanceProperty.get().setValue(newValue);
1741 List<String> path = new ArrayList<>();
1742 path.add(componentInstanceUniqueId);
1744 instanceProperty.get().setPath(path);
1745 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
1746 if (status != StorageOperationStatus.OK) {
1747 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1748 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1751 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1757 return componentsUtils.getResponseFormat(ActionStatus.OK);
1760 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1761 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1762 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1763 StorageOperationStatus status;
1764 instanceProperty.get().setValue(newValue);
1765 if (instanceProperty.isPresent()) {
1766 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1768 status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
1770 if (status != StorageOperationStatus.OK) {
1771 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1772 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1774 List<String> path = new ArrayList<>();
1775 path.add(foundResourceInstance.getUniqueId());
1776 property.setPath(path);
1778 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1779 return componentsUtils.getResponseFormat(ActionStatus.OK);
1782 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1783 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1784 if (allDataTypesEither.isRight()) {
1785 TitanOperationStatus status = allDataTypesEither.right().value();
1786 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1787 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
1789 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1790 String innerType = null;
1791 String propertyType = property.getType();
1792 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1793 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1795 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1796 SchemaDefinition def = property.getSchema();
1798 log.debug("Schema doesn't exists for property of type {}", type);
1799 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1801 PropertyDataDefinition propDef = def.getProperty();
1802 if (propDef == null) {
1803 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1804 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1806 innerType = propDef.getType();
1808 // Specific Update Logic
1809 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1810 String newValue = property.getValue();
1811 if (isValid.isRight()) {
1812 Boolean res = isValid.right().value();
1814 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1817 Object object = isValid.left().value();
1818 if (object != null) {
1819 newValue = object.toString();
1823 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1824 if (pair.getRight() != null && pair.getRight() == false) {
1825 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1826 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
1829 return Either.left(newValue);
1832 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1833 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
1834 Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
1835 StorageOperationStatus status;
1836 if (instanceProperty.isPresent()) {
1837 instanceProperty.get().setValue(input.getValue());
1838 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1840 status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1842 if (status != StorageOperationStatus.OK) {
1843 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1844 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1846 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1847 return componentsUtils.getResponseFormat(ActionStatus.OK);
1850 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1852 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1854 validateUserExists(userId, "create Or Update Property Value", false);
1856 if (componentTypeEnum == null) {
1857 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1858 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1861 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1863 if (getResourceResult.isRight()) {
1864 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1865 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1868 Component containerComponent = getResourceResult.left().value();
1870 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1871 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1872 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1875 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1876 if (resourceInstanceStatus.isRight()) {
1877 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
1881 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1884 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1885 if (lockStatus != StorageOperationStatus.OK) {
1886 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1887 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1891 for (ComponentInstanceInput input: inputs) {
1892 Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
1893 updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
1897 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1899 if (updateContainerRes.isRight()) {
1900 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1901 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1904 resultOp = Either.left(inputs);
1908 if (resultOp == null || resultOp.isRight()) {
1909 titanDao.rollback();
1914 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1919 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
1922 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
1924 validateUserExists(userId, "create Or Update Property Value", false);
1926 if (componentTypeEnum == null) {
1927 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1928 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1932 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
1933 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
1934 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1938 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1939 if (lockStatus != StorageOperationStatus.OK) {
1940 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1941 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1945 String propertyValueUid = property.getValueUniqueUid();
1947 if (propertyValueUid == null) {
1949 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
1951 if (counterRes.isRight()) {
1952 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
1953 StorageOperationStatus status = counterRes.right().value();
1954 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1955 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
1957 Integer index = counterRes.left().value();
1958 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
1960 if (result.isLeft()) {
1961 log.trace("Property value was added to resource instance {}", resourceInstanceId);
1962 ComponentInstanceProperty instanceProperty = result.left().value();
1964 resultOp = Either.left(instanceProperty);
1967 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
1969 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1971 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1975 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
1977 if (result.isLeft()) {
1978 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
1979 ComponentInstanceProperty instanceProperty = result.left().value();
1981 resultOp = Either.left(instanceProperty);
1984 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
1986 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
1988 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1991 if (resultOp.isLeft()) {
1992 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
1993 if (updateCustomizationUUID != StorageOperationStatus.OK) {
1994 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
1996 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2003 if (resultOp == null || resultOp.isRight()) {
2004 titanDao.rollback();
2009 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2014 public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
2016 Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
2018 validateUserExists(userId, "create Or Update Input Value", false);
2020 if (componentTypeEnum == null) {
2021 BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2022 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2026 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2027 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2028 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2032 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2033 if (lockStatus != StorageOperationStatus.OK) {
2034 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2035 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2039 String propertyValueUid = inputProperty.getValueUniqueUid();
2040 if (propertyValueUid == null) {
2042 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
2044 if (counterRes.isRight()) {
2045 log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
2046 StorageOperationStatus status = counterRes.right().value();
2047 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2048 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2050 Integer index = counterRes.left().value();
2051 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
2053 if (result.isLeft()) {
2054 log.debug("Property value was added to resource instance {}", resourceInstanceId);
2055 ComponentInstanceInput instanceProperty = result.left().value();
2057 resultOp = Either.left(instanceProperty);
2061 log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
2063 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2065 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2071 Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
2073 if (result.isLeft()) {
2074 log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
2075 ComponentInstanceInput instanceProperty = result.left().value();
2077 resultOp = Either.left(instanceProperty);
2081 log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
2083 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2085 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2092 if (resultOp == null || resultOp.isRight()) {
2093 titanDao.rollback();
2098 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2103 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
2105 validateUserExists(userId, "delete Property Value", false);
2107 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2109 if (componentTypeEnum == null) {
2110 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2111 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2115 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2116 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2117 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2121 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2122 if (lockStatus != StorageOperationStatus.OK) {
2123 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2124 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2128 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2130 if (result.isLeft()) {
2131 log.debug("Property value {} was removed from graph.", propertyValueId);
2132 ComponentInstanceProperty instanceProperty = result.left().value();
2134 resultOp = Either.left(instanceProperty);
2138 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2140 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2142 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2148 if (resultOp == null || resultOp.isRight()) {
2149 titanDao.rollback();
2154 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2159 private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
2161 Either<Component, ResponseFormat> eitherResponse = null;
2162 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
2163 Component component;
2164 ResponseFormat errorResponse;
2165 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2166 if (getComponentRes.isRight()) {
2167 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2168 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2169 errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2170 eitherResponse = Either.right(errorResponse);
2172 if (eitherResponse == null) {
2173 component = getComponentRes.left().value();
2174 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2175 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2176 ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
2177 errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
2178 eitherResponse = Either.right(errorResponse);
2181 if (eitherResponse == null) {
2182 eitherResponse = Either.left(getComponentRes.left().value());
2184 return eitherResponse;
2187 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2188 String containerComponentId,
2189 String componentInstanceId,
2190 ComponentInstance newComponentInstance) {
2191 Either<Set<String>, ResponseFormat> resultOp;
2192 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2193 if (validateComponentType.isRight()) {
2194 return Either.right(validateComponentType.right().value());
2196 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2197 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2200 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
2201 validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2202 if (validateComponentExists.isRight()) {
2203 return Either.right(validateComponentExists.right().value());
2205 Component containerComponent = validateComponentExists.left().value();
2207 //Fetch current component instance
2208 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2209 getResourceInstanceById(containerComponent, componentInstanceId);
2210 if (eitherResourceInstance.isRight()) {
2211 resultOp = Either.right(componentsUtils.getResponseFormat(
2212 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2215 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2217 //Check whether new componentInstance exists
2218 String resourceId = newComponentInstance.getComponentUid();
2219 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2220 if (componentExistsRes.isRight()) {
2221 log.debug("Failed to find resource {} ", resourceId);
2222 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2223 (componentExistsRes.right().value()), resourceId));
2225 } else if (!componentExistsRes.left().value()) {
2226 log.debug("The resource {} not found ", resourceId);
2227 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2231 //Fetch component using new component instance uid
2232 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2233 if (eitherResourceName.isRight()) {
2234 resultOp = Either.right(eitherResourceName.right().value());
2237 Component updatedContainerComponent=eitherResourceName.left().value();
2238 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2239 currentResourceInstance, updatedContainerComponent);
2240 resultOp=Either.left(toDeleteForwardingPaths);
2245 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2246 Component updatedContainerComponent) {
2247 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2248 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
2250 Service service = (Service) containerComponent;
2251 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2253 return forwardingPathUtils.
2254 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2257 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2258 ComponentParametersView componentParametersView = new ComponentParametersView();
2259 componentParametersView.setIgnoreCapabiltyProperties(false);
2260 componentParametersView.setIgnoreForwardingPath(false);
2261 return componentParametersView;
2264 public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2266 User user = validateUserExists(userId, "change Component Instance Version", false);
2268 Either<ComponentInstance, ResponseFormat> resultOp = null;
2270 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
2271 if (validateComponentType.isRight()) {
2272 return Either.right(validateComponentType.right().value());
2275 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
2276 ComponentParametersView componentParametersView = new ComponentParametersView();
2277 componentParametersView.setIgnoreCapabiltyProperties(false);
2278 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2279 if (validateComponentExists.isRight()) {
2280 return Either.right(validateComponentExists.right().value());
2282 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
2284 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
2285 if (validateCanWorkOnComponent.isRight()) {
2286 return Either.right(validateCanWorkOnComponent.right().value());
2289 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2290 if (resourceInstanceStatus.isRight()) {
2291 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2295 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2297 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2300 public Either<ComponentInstance, ResponseFormat> changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2301 ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
2302 Either<ComponentInstance, ResponseFormat> resultOp = null;
2303 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2305 Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
2306 String containerComponentId = containerComponent.getUniqueId();
2307 String componentInstanceId = currentResourceInstance.getUniqueId();
2308 if (lockComponent.isRight()) {
2309 return Either.right(lockComponent.right().value());
2315 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2316 resultOp = Either.left(currentResourceInstance);
2320 String resourceId = newComponentInstance.getComponentUid();
2324 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2325 if (componentExistsRes.isRight()) {
2326 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
2327 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
2329 } else if (!componentExistsRes.left().value()) {
2330 log.debug("The resource {} not found ", resourceId);
2331 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2335 Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2337 if (eitherOriginComponent.isRight()) {
2338 resultOp = Either.right(eitherOriginComponent.right().value());
2341 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
2342 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2343 if (resultOp.isRight()) {
2344 log.debug("failed to delete resource instance {}", resourceId);
2347 ComponentInstance resResourceInfo = resultOp.left().value();
2348 Component origComponent = null;
2349 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2350 if (originType == OriginTypeEnum.ServiceProxy) {
2351 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2352 if (serviceProxyOrigin.isRight()) {
2353 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
2354 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
2356 origComponent = serviceProxyOrigin.left().value();
2358 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2360 if (fillProxyRes != StorageOperationStatus.OK) {
2361 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2362 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
2365 newComponentInstance.setOriginType(originType);
2369 Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
2371 if (eitherResourceName.isRight()) {
2372 resultOp = Either.right(eitherResourceName.right().value());
2376 origComponent = eitherResourceName.left().value();
2378 newComponentInstance.setName(resResourceInfo.getName());
2381 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2382 newComponentInstance.setPosX(resResourceInfo.getPosX());
2383 newComponentInstance.setPosY(resResourceInfo.getPosY());
2384 newComponentInstance.setDescription(resResourceInfo.getDescription());
2386 resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2388 if (resultOp.isRight()) {
2389 log.debug("failed to create resource instance {}", resourceId);
2393 ComponentInstance updatedComponentInstance = resultOp.left().value();
2394 if (resultOp.isRight()) {
2395 log.debug("failed to create resource instance {}", resourceId);
2399 dataHolder.setCurrInstanceNode(origComponent);
2400 Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2401 if (mergeStatusEither.isRight()) {
2402 return Either.right(mergeStatusEither.right().value());
2405 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2406 if (postChangeVersionResult != ActionStatus.OK) {
2407 return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
2410 ComponentParametersView filter = new ComponentParametersView(true);
2411 filter.setIgnoreComponentInstances(false);
2412 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2413 if (updatedComponentRes.isRight()) {
2414 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2415 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2416 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
2417 log.debug("Component with id {} was not found", containerComponentId);
2418 return Either.right(responseFormat);
2420 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2421 if (resourceInstanceStatus.isRight()) {
2422 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
2425 resultOp = Either.left(resourceInstanceStatus.left().value());
2429 unlockComponent(resultOp, containerComponent);
2434 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2435 final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
2436 Component containerComponent = null;
2438 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2440 validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
2442 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
2443 if (validateComponentType.isRight()) {
2444 resultOp = Either.right(validateComponentType.right().value());
2448 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2449 if (validateContainerComponentExists.isRight()) {
2450 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2453 containerComponent = validateContainerComponentExists.left().value();
2455 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2456 if (resourceInstanceStatus.isRight()) {
2457 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2461 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2462 if (CollectionUtils.isEmpty(instanceProperties)) {
2463 instanceProperties = new ArrayList<>();
2465 resultOp = Either.left(instanceProperties);
2468 unlockComponent(resultOp, containerComponent);
2472 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2473 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2475 if (counterRes.isRight()) {
2476 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2477 StorageOperationStatus status = counterRes.right().value();
2478 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2479 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2481 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2487 * updates componentInstance modificationTime
2489 * @param componentInstance
2490 * @param componentInstanceType
2491 * @param modificationTime
2492 * @param inTransaction
2495 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2496 Either<ComponentInstanceData, ResponseFormat> result;
2497 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2499 if (updateComponentInstanceRes.isRight()) {
2500 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2501 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2503 result = Either.left(updateComponentInstanceRes.left().value());
2508 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2509 // TODO Add implementation
2510 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2514 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2515 // TODO Add implementation
2516 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2520 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2521 // TODO Add implementation
2522 Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
2526 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2527 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2530 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2532 Either<ComponentInstance, StorageOperationStatus> result = null;
2533 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2534 Optional<ComponentInstance> foundInstance = null;
2535 if (CollectionUtils.isEmpty(instances)) {
2536 result = Either.right(StorageOperationStatus.NOT_FOUND);
2538 if (result == null) {
2539 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2540 if (!foundInstance.isPresent()) {
2541 result = Either.right(StorageOperationStatus.NOT_FOUND);
2544 if (result == null) {
2545 result = Either.left(foundInstance.get());
2550 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2552 Long creationDate = origInstanceForUpdate.getCreationTime();
2554 Long modificationTime = System.currentTimeMillis();
2555 resourceInstanceForUpdate.setCreationTime(creationDate);
2556 resourceInstanceForUpdate.setModificationTime(modificationTime);
2558 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2560 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2561 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2564 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2566 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2567 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2569 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2570 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2572 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2573 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2575 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2576 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2578 if (resourceInstanceForUpdate.getOriginType() == null) {
2579 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2581 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2582 resourceInstanceForUpdate.setIsProxy(true);
2583 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2584 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2586 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2587 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2589 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2590 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2592 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2593 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2595 return resourceInstanceForUpdate;
2598 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2599 * @param containerComponentType
2600 * @param containerComponentId
2601 * @param componentInstanceUniqueId
2602 * @param capabilityType
2603 * @param capabilityName
2608 public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2610 Component containerComponent = null;
2612 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2614 validateUserExists(userId, "Get Component Instance Properties By Id", false);
2615 if(resultOp == null){
2616 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
2617 if (validateComponentType.isRight()) {
2618 resultOp = Either.right(validateComponentType.right().value());
2621 if(resultOp == null){
2622 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
2623 if (validateContainerComponentExists.isRight()) {
2624 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
2626 containerComponent = validateContainerComponentExists.left().value();
2629 if(resultOp == null){
2630 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2631 if (resourceInstanceStatus.isRight()) {
2632 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2634 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
2639 unlockComponent(resultOp, containerComponent);
2643 private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2644 Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
2645 CapabilityDefinition foundCapability;
2646 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2647 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2648 if (capabilitiesPerType != null) {
2649 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2650 if (capabilityOpt.isPresent()) {
2651 foundCapability = capabilityOpt.get();
2652 result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
2656 if (result == null) {
2657 result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2662 private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2663 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2665 Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
2666 if(getComponentInstanceCapabilityProperties != null) {
2667 if (getComponentInstanceCapabilityProperties.isRight()) {
2668 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
2670 resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
2673 resultOp = Either.left(new ArrayList<>());
2675 } catch(Exception e){
2676 log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2677 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2682 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2683 String capabilityType, String capabilityName, String ownerId) {
2684 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2685 StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
2686 sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
2687 String capKey = sb.toString();
2689 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2690 .orElse(Collections.emptyMap());
2691 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2692 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2693 if (cap.isPresent()) {
2694 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2695 if (capProperties != null) {
2696 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2697 StorageOperationStatus status;
2698 if (instanceProperty.isPresent()) {
2699 instanceProperty.get().setValue(newValue);
2700 List<String> path = new ArrayList<>();
2701 path.add(componentInstanceUniqueId);
2703 instanceProperty.get().setPath(path);
2704 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2705 if (status != StorageOperationStatus.OK) {
2706 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2707 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2710 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2714 return componentsUtils.getResponseFormat(ActionStatus.OK);
2717 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2718 List<ComponentInstanceProperty> properties, String userId) {
2719 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2721 validateUserExists(userId, "update instance capability property", false);
2723 if (componentTypeEnum == null) {
2724 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2725 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2727 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2729 if (getResourceResult.isRight()) {
2730 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2731 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2733 Component containerComponent = getResourceResult.left().value();
2735 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2736 log.info("Restricted operation for user: {sourcePropList} on component {}", userId, containerComponentId);
2737 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2739 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2740 if (resourceInstanceStatus.isRight()) {
2741 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2743 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2745 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2746 if (lockStatus != StorageOperationStatus.OK) {
2747 log.debug("Failed to lock component {}", containerComponentId);
2748 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2751 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2752 if (allDataTypes.isRight()) {
2753 TitanOperationStatus status = allDataTypes.right().value();
2754 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2755 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
2759 for (ComponentInstanceProperty property : properties) {
2760 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2761 newPropertyValueEither.bimap(updatedValue ->
2762 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2765 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2767 if (updateContainerRes.isRight()) {
2768 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2769 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2772 resultOp = Either.left(properties);
2776 if (resultOp == null || resultOp.isRight()) {
2777 titanDao.rollback();
2782 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2786 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2787 List<ComponentInstanceProperty> properties, String userId) {
2788 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2790 validateUserExists(userId, "update instance capability property", false);
2792 if (componentTypeEnum == null) {
2793 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2794 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2796 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2798 if (getResourceResult.isRight()) {
2799 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2800 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2802 Component containerComponent = getResourceResult.left().value();
2804 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2805 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2806 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2808 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2809 if (resourceInstanceStatus.isRight()) {
2810 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2812 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2814 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2815 if (lockStatus != StorageOperationStatus.OK) {
2816 log.debug("Failed to lock component {}", containerComponentId);
2817 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2821 for (ComponentInstanceProperty property : properties) {
2822 Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
2823 newPropertyValueEither.bimap(updatedValue ->
2824 updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2827 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2829 if (updateContainerRes.isRight()) {
2830 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2831 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2834 resultOp = Either.left(properties);
2838 if (resultOp == null || resultOp.isRight()) {
2839 titanDao.rollback();
2844 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2848 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2849 String containerComponentId,
2850 String componentInstanceId,
2853 Map<String, ComponentInstance> resultMap = new HashMap<>();
2854 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2855 if (getOrigComponent.isRight()) {
2856 log.error("Failed to get the original component information");
2857 return Either.right(componentsUtils.getResponseFormat(
2858 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2861 Component origComponent = getOrigComponent.left().value();
2863 Either<Boolean, ResponseFormat> lockComponent = lockComponent(origComponent, "copyComponentInstance");
2864 if (lockComponent.isRight()) {
2865 log.error("destComponentInstance's data is {}", origComponent.toString());
2866 return Either.right(lockComponent.right().value());
2870 Either<ComponentInstance, ResponseFormat> actionResponse = null;
2872 actionResponse = createComponentInstance(
2873 "services", containerComponentId, userId, inputComponentInstance, true, false);
2875 if (actionResponse.isRight()) {
2876 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
2877 return Either.right(componentsUtils.getResponseFormat(
2878 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2883 // on failure of the create instance unlock the resource and rollback the transaction.
2884 if (null == actionResponse || actionResponse.isRight()) {
2885 titanDao.rollback();
2887 unlockComponent(actionResponse, origComponent);
2890 Either<String, ResponseFormat> resultOp = null;
2893 ComponentInstance destComponentInstance = actionResponse.left().value();
2894 log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2897 resultOp = deepCopyComponentInstance(
2898 origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2900 if (resultOp.isRight()) {
2901 log.error("Failed to deep copy component instance");
2902 return Either.right(componentsUtils.getResponseFormat(
2903 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2905 resultMap.put("componentInstance", destComponentInstance);
2906 return Either.left(resultMap);
2909 if (resultOp == null || resultOp.isRight()) {
2910 titanDao.rollback();
2914 log.debug("Success trasaction commit");
2917 unlockComponent(resultOp, origComponent);
2921 private Either<String, ResponseFormat> deepCopyComponentInstance(
2922 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2923 ComponentInstance destComponentInstance, String userId) {
2925 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2926 if (getDestComponent.isRight()) {
2927 log.error("Failed to get the dest component information");
2928 return Either.right(componentsUtils.getResponseFormat(
2929 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2932 Component destComponent = getDestComponent.left().value();
2934 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2935 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2936 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2937 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2938 return Either.right(componentsUtils.getResponseFormat(
2939 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2942 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2943 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2944 if (copyComponentInstanceWithAttributes.isRight()) {
2945 log.error("Failed to copy component instance with attributes as part of deep copy");
2946 return Either.right(componentsUtils.getResponseFormat(
2947 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2949 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2952 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2953 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2954 ComponentInstance destComponentInstance, String userId) {
2955 log.debug("start to copy ComponentInstance with properties and inputs");
2957 List<ComponentInstanceProperty> sourcePropList = null;
2958 if (sourceComponent.getComponentInstancesProperties() != null
2959 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2960 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2961 log.debug("sourcePropList");
2964 List<ComponentInstanceProperty> destPropList = null;
2965 String destComponentInstanceId = destComponentInstance.getUniqueId();
2966 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2967 if (destComponent.getComponentInstancesProperties() != null
2968 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2969 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2970 log.debug("destPropList {}");
2973 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2975 if (null != destPropList && null != sourcePropList) {
2976 log.debug("start to set property and attribute");
2977 for (ComponentInstanceProperty destProp : destPropList) {
2978 String destPropertyName = destProp.getName();
2979 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2980 if (!destPropertyName.equals(sourceProp.getName())) {
2983 log.debug("now set property");
2984 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2985 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2986 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2988 destProp.setValue(sourceProp.getValue());
2989 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2990 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2991 if (updatePropertyValueEither.isRight()) {
2992 log.error("Failed to copy the property {}", destPropertyName);
2993 return Either.right(componentsUtils.getResponseFormat(
2994 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2999 log.debug("Now start to update inputs");
3001 if (sourceProp.getGetInputValues() != null) {
3002 if (sourceProp.getGetInputValues().isEmpty()) {
3003 log.debug("source property input values empty");
3006 log.debug("Now starting to copy the {} property", destPropertyName);
3008 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
3009 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
3010 if (getSourceInputDefaultValue.isRight()) {
3011 return Either.right(getSourceInputDefaultValue.right().value());
3013 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
3018 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3021 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
3022 Component destComponent,
3023 String sourceComponentInstanceId,
3024 ComponentInstance destComponentInstance,
3026 String destComponentInstanceId = destComponentInstance.getUniqueId();
3028 log.info("start to copy component instance with attributes");
3030 List<ComponentInstanceProperty> sourceAttributeList = null;
3031 if (sourceComponent.getComponentInstancesAttributes() != null
3032 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
3033 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
3034 log.info("sourceAttributes {}");
3037 List<ComponentInstanceProperty> destAttributeList = null;
3038 if (destComponent.getComponentInstancesAttributes() != null
3039 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
3040 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
3041 log.info("destAttributeList {}");
3043 if (null != sourceAttributeList && null != destAttributeList) {
3044 log.info("set attribute");
3046 for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
3047 String sourceAttributeName = sourceAttribute.getName();
3048 for (ComponentInstanceProperty destAttribute : destAttributeList) {
3049 if (sourceAttributeName.equals(destAttribute.getName())) {
3050 if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
3051 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
3053 sourceAttribute.setUniqueId(
3054 UniqueIdBuilder.buildResourceInstanceUniuqeId(
3055 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
3057 Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
3058 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
3059 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
3061 if (updateAttributeValueEither.isRight()) {
3062 log.error("Failed to copy the attribute");
3063 return Either.right(componentsUtils
3064 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3065 "Failed to paste component instance to the canvas, attribute copy"));
3074 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3077 private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
3079 String resourceInstanceId,
3080 ComponentInstanceProperty attribute,
3083 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
3085 validateUserExists(userId, "Create or Update attribute value", false);
3087 if (componentTypeEnum == null) {
3088 BeEcompErrorManager.getInstance().logInvalidInputError(
3089 "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3090 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3094 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3096 if (getResourceResult.isRight()) {
3097 log.info("Failed to retrieve component id {}", componentId);
3098 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3102 Component containerComponent = getResourceResult.left().value();
3104 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3106 if (resourceInstanceStatus.isRight()) {
3107 resultOp = Either.right(componentsUtils.getResponseFormat(
3108 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3112 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3115 String propertyType = attribute.getType();
3116 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3117 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3119 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3120 SchemaDefinition def = attribute.getSchema();
3122 log.info("Schema doesn't exists for attribute of type {}", type);
3123 return Either.right(componentsUtils.getResponseFormat(
3124 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3126 PropertyDataDefinition propDef = def.getProperty();
3127 if (propDef == null) {
3128 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3129 return Either.right(componentsUtils.getResponseFormat(
3130 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3134 List<ComponentInstanceProperty> instanceAttributes = containerComponent.
3135 getComponentInstancesAttributes().get(resourceInstanceId);
3136 Optional<ComponentInstanceProperty> instanceAttribute =
3137 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3138 StorageOperationStatus status;
3140 if (instanceAttribute.isPresent()) {
3141 log.info("updateComponentInstanceAttribute");
3142 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3144 log.info("addComponentInstanceAttribute");
3145 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3147 if (status != StorageOperationStatus.OK) {
3148 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3149 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3152 List<String> path = new ArrayList<>();
3153 path.add(foundResourceInstance.getUniqueId());
3154 attribute.setPath(path);
3156 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3157 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3158 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3160 if (updateContainerRes.isRight()) {
3161 ActionStatus actionStatus = componentsUtils.
3162 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3163 resultOp = Either.right(componentsUtils.
3164 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3167 resultOp = Either.left(attribute);
3174 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3175 String componentInstanceId,
3176 ComponentInstanceProperty property) {
3177 Either<String, ResponseFormat> resultOp;
3178 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3180 if (getComponent.isRight()) {
3181 log.error("Failed to get the component information");
3182 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3183 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3186 Component containerComponent = getComponent.left().value();
3188 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3189 containerComponent, componentInstanceId, property);
3190 if (status != StorageOperationStatus.OK) {
3191 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3192 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3196 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3197 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3199 if (updateContainerRes.isRight()) {
3200 ActionStatus actionStatus = componentsUtils.
3201 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3202 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3206 return Either.left("Update OK");
3209 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3210 List<InputDefinition> inputList = component.getInputs();
3211 for (InputDefinition input : inputList) {
3212 if (input.getUniqueId().equals(inputId)) {
3213 if (input.getDefaultValue() == null) {
3214 log.debug("The input's default value is null");
3215 return Either.left(null);
3217 return Either.left(input.getDefaultValue());
3220 log.error("The input's default value with id {} is not found", inputId);
3221 return Either.right(componentsUtils.getResponseFormat(
3222 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3226 * Method to delete selected nodes and edges on composition page
3227 * @param containerComponentType
3228 * @param componentId
3229 * @param componentInstanceIdList
3233 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3235 List<String> componentInstanceIdList,
3238 List<String> deleteErrorIds = new ArrayList<>();
3239 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3240 Either<Component, ResponseFormat> validateResponse = validateUser(containerComponentType, componentId, userId);
3241 if (validateResponse.isRight()) {
3242 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3243 return deleteErrorMap;
3245 Component containerComponent = validateResponse.left().value();
3247 Either<Boolean, ResponseFormat> lockComponent = lockComponent(
3248 containerComponent, "batchDeleteComponentInstance");
3249 if (lockComponent.isRight()) {
3250 log.error("Failed to lockComponent containerComponent");
3251 deleteErrorMap.put("deleteFailedIds", componentInstanceIdList);
3252 return deleteErrorMap;
3256 for (String eachInstanceId : componentInstanceIdList) {
3257 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3258 containerComponent, containerComponentType, componentId, eachInstanceId);
3259 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3260 if (actionResponse.isRight()) {
3261 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3262 deleteErrorIds.add(eachInstanceId);
3265 //sending the ids of the error nodes that were not deleted to UI
3266 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3267 return deleteErrorMap;
3269 unlockComponent(validateResponse, containerComponent);
3273 private Either<Component, ResponseFormat> validateUser(String containerComponentParam,
3274 String containerComponentId,
3276 validateUserExists(userId, "delete Component Instance", false);
3277 Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
3278 if (validateComponentType.isRight()) {
3279 log.error("ComponentType[{}] doesn't support", containerComponentParam);
3280 return Either.right(validateComponentType.right().value());
3283 final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
3284 Either<Component, ResponseFormat> validateComponentExists = validateComponentExists(
3285 containerComponentId, containerComponentType, null);
3286 if (validateComponentExists.isRight()) {
3287 log.error("Component Id[{}] doesn't exist", containerComponentId);
3288 return Either.right(validateComponentExists.right().value());
3291 Component containerComponent = validateComponentExists.left().value();
3292 Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
3293 if (validateCanWorkOnComponent.isRight()) {
3294 return Either.right(validateCanWorkOnComponent.right().value());
3296 return Either.left(containerComponent);
3299 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3300 String containerComponentType,
3301 String containerComponentId,
3302 String componentInstanceId) {
3304 Either<ComponentInstance, ResponseFormat> resultOp;
3305 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3307 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3309 if (resultOp.isRight()) {
3310 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3311 return Either.right(resultOp.right().value());
3314 log.info("Successfully deleted instance with id {}", componentInstanceId);
3315 return Either.left(resultOp.left().value());