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=========================================================
20 package org.openecomp.sdc.be.components.impl;
22 import static org.openecomp.sdc.be.components.attribute.GetOutputUtils.isGetOutputValueForOutput;
23 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
24 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityOfChildInstance;
26 import com.google.common.collect.Sets;
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
38 import java.util.Optional;
40 import java.util.UUID;
41 import java.util.stream.Collectors;
42 import org.apache.commons.collections.CollectionUtils;
43 import org.apache.commons.collections.MapUtils;
44 import org.apache.commons.lang3.StringUtils;
45 import org.apache.commons.lang3.tuple.ImmutablePair;
46 import org.onap.sdc.tosca.datatypes.model.PropertyType;
47 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
48 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
49 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
50 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
51 import org.openecomp.sdc.be.components.impl.exceptions.ToscaGetFunctionExceptionSupplier;
52 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
53 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtil;
54 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
55 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
56 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
57 import org.openecomp.sdc.be.components.validation.ComponentValidations;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
60 import org.openecomp.sdc.be.config.ConfigurationManager;
61 import org.openecomp.sdc.be.dao.api.ActionStatus;
62 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
63 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
64 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
65 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
66 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
67 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
74 import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
75 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
76 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
77 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
78 import org.openecomp.sdc.be.datatypes.enums.PropertySource;
79 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
80 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
81 import org.openecomp.sdc.be.exception.BusinessException;
82 import org.openecomp.sdc.be.impl.ComponentsUtils;
83 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
84 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
85 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
86 import org.openecomp.sdc.be.model.ArtifactDefinition;
87 import org.openecomp.sdc.be.model.AttributeDefinition;
88 import org.openecomp.sdc.be.model.CapabilityDefinition;
89 import org.openecomp.sdc.be.model.Component;
90 import org.openecomp.sdc.be.model.ComponentInstance;
91 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
92 import org.openecomp.sdc.be.model.ComponentInstanceInput;
93 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
94 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
95 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
96 import org.openecomp.sdc.be.model.ComponentParametersView;
97 import org.openecomp.sdc.be.model.DataTypeDefinition;
98 import org.openecomp.sdc.be.model.GroupDefinition;
99 import org.openecomp.sdc.be.model.InputDefinition;
100 import org.openecomp.sdc.be.model.InterfaceDefinition;
101 import org.openecomp.sdc.be.model.LifecycleStateEnum;
102 import org.openecomp.sdc.be.model.OutputDefinition;
103 import org.openecomp.sdc.be.model.PolicyDefinition;
104 import org.openecomp.sdc.be.model.PropertyDefinition;
105 import org.openecomp.sdc.be.model.RelationshipInfo;
106 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
107 import org.openecomp.sdc.be.model.RequirementDefinition;
108 import org.openecomp.sdc.be.model.Resource;
109 import org.openecomp.sdc.be.model.Service;
110 import org.openecomp.sdc.be.model.User;
111 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
112 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
113 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
114 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
115 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
116 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
117 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
119 import org.openecomp.sdc.be.model.operations.StorageException;
120 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
121 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
122 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
123 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
124 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
125 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
126 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
127 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
128 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
129 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
130 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
131 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
132 import org.openecomp.sdc.be.user.Role;
133 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
134 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
135 import org.openecomp.sdc.common.api.Constants;
136 import org.openecomp.sdc.common.datastructure.Wrapper;
137 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
138 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
139 import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData;
140 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
141 import org.openecomp.sdc.common.log.wrappers.Logger;
142 import org.openecomp.sdc.common.util.ValidationUtils;
143 import org.openecomp.sdc.exception.ResponseFormat;
144 import org.springframework.beans.factory.annotation.Autowired;
146 @org.springframework.stereotype.Component
147 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
149 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class);
150 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
151 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
152 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
153 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
154 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
155 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
156 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
157 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
158 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
159 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
160 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
161 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
162 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
163 private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE = "Cannot attach resource instances to container resource of type {}";
164 private static final String FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY = "Failed to update component instance capability on instance {} in "
166 private static final String SERVICE_PROXY = "serviceProxy";
167 private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI";
168 private static final String COMPONENT_ARCHIVED = "Component is archived. Component id: {}";
169 private static final String RESTRICTED_OPERATION_ON_SERVIVE = "Restricted operation for user: {} on service {}";
170 private static final String FAILED_TO_LOCK_COMPONENT = "Failed to lock component {}";
171 private static final String RESTRICTED_OPERATION_ON_COMPONENT = "Restricted operation for user: {} on component {}";
172 private static final String RESOURCE_INSTANCE = "resource instance";
173 private static final String SERVICE = "service";
175 private final ComponentInstanceOperation componentInstanceOperation;
176 private final ArtifactsBusinessLogic artifactBusinessLogic;
177 private final ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
178 private final ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
179 private final ForwardingPathOperation forwardingPathOperation;
180 private final NodeFilterOperation nodeFilterOperation;
182 private CompositionBusinessLogic compositionBusinessLogic;
184 private ContainerInstanceTypesData containerInstanceTypesData;
187 public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
188 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
189 InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
190 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
191 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
192 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
193 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
194 ArtifactsOperations artifactToscaOperation) {
195 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
196 artifactToscaOperation);
197 this.componentInstanceOperation = componentInstanceOperation;
198 this.artifactBusinessLogic = artifactBusinessLogic;
199 this.compInstMergeDataBL = compInstMergeDataBL;
200 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
201 this.forwardingPathOperation = forwardingPathOperation;
202 this.nodeFilterOperation = nodeFilterOperation;
205 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId,
206 ComponentInstance resourceInstance) {
207 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
210 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
211 List<ComponentInstanceProperty> resList = new ArrayList<>();
212 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
213 if (ciPropertiesMap != null && !ciPropertiesMap.isEmpty()) {
214 ciPropertiesMap.forEach((s, ciPropList) -> {
216 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
217 if (ciOp.isPresent()) {
218 ciName = ciOp.get().getName();
220 if (ciPropList != null && !ciPropList.isEmpty()) {
221 for (ComponentInstanceProperty prop : ciPropList) {
222 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
223 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
231 public List<ComponentInstanceAttribute> getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component,
232 final String outputId) {
233 final List<ComponentInstanceAttribute> resList = new ArrayList<>();
234 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = component.getComponentInstancesAttributes();
235 if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) {
236 componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> {
238 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
240 if (ciOp.isPresent()) {
241 ciName = ciOp.get().getName();
243 if (componentInstanceAttributeList != null && !componentInstanceAttributeList.isEmpty()) {
244 for (final ComponentInstanceAttribute compInstanceAttribute : componentInstanceAttributeList) {
245 List<GetOutputValueDataDefinition> outputValues = compInstanceAttribute.getGetOutputValues();
246 addCompInstanceAttribute(s, ciName, compInstanceAttribute, outputValues, outputId, resList);
254 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues,
255 String inputId, List<ComponentInstanceProperty> resList) {
256 if (inputsValues != null && !inputsValues.isEmpty()) {
257 for (GetInputValueDataDefinition inputData : inputsValues) {
258 if (isGetInputValueForInput(inputData, inputId)) {
259 prop.setComponentInstanceId(s);
260 prop.setComponentInstanceName(ciName);
268 private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute,
269 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
270 final List<ComponentInstanceAttribute> resList) {
271 if (outputsValues != null && !outputsValues.isEmpty()) {
272 for (final GetOutputValueDataDefinition outputData : outputsValues) {
273 if (isGetOutputValueForOutput(outputData, outputId)) {
274 attribute.setComponentInstanceId(s);
275 attribute.setComponentInstanceName(ciName);
276 resList.add(attribute);
283 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) {
284 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
285 if (propertyCandidate.isPresent()) {
286 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
287 Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
289 .ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
290 return Optional.of(componentInstanceProperty);
292 return Optional.empty();
295 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
296 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
297 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
298 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
299 if (CollectionUtils.isNotEmpty(getPolicyValues)) {
300 getPolicyValues.remove(getPolicyValue);
301 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
302 policyDefinition.setGetPolicyValues(getPolicyValues);
306 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
307 ComponentInstanceProperty componentInstanceProperty) {
308 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
309 return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName()))
313 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) {
314 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
315 if (MapUtils.isEmpty(componentInstancesProperties)) {
316 return Optional.empty();
318 String instanceUniqueId = policy.getInstanceUniqueId();
319 List<ComponentInstanceProperty> componentInstanceProperties =
320 componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>();
321 return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny();
324 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
325 List<ComponentInstanceInput> resList = new ArrayList<>();
326 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
327 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
328 ciInputsMap.forEach((s, ciPropList) -> {
330 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
331 if (ciOp.isPresent()) {
332 ciName = ciOp.get().getName();
334 if (ciPropList != null && !ciPropList.isEmpty()) {
335 for (ComponentInstanceInput prop : ciPropList) {
336 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
337 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
345 public List<ComponentInstanceOutput> getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component,
346 final String outputId) {
347 final List<ComponentInstanceOutput> resList = new ArrayList<>();
348 final Map<String, List<ComponentInstanceOutput>> ciInputsMap = component.getComponentInstancesOutputs();
349 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
350 ciInputsMap.forEach((s, ciPropList) -> {
352 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
354 if (ciOp.isPresent()) {
355 ciName = ciOp.get().getName();
357 if (ciPropList != null && !ciPropList.isEmpty()) {
358 for (final ComponentInstanceOutput prop : ciPropList) {
359 final List<GetOutputValueDataDefinition> outputValues = prop.getGetOutputValues();
360 addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList);
368 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues,
369 String inputId, List<ComponentInstanceInput> resList) {
370 if (inputsValues != null && !inputsValues.isEmpty()) {
371 for (GetInputValueDataDefinition inputData : inputsValues) {
372 if (isGetInputValueForInput(inputData, inputId)) {
373 prop.setComponentInstanceId(s);
374 prop.setComponentInstanceName(ciName);
382 private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop,
383 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
384 final List<ComponentInstanceOutput> resList) {
385 if (outputsValues != null && !outputsValues.isEmpty()) {
386 for (final GetOutputValueDataDefinition outputData : outputsValues) {
387 if (isGetOutputValueForOutput(outputData, outputId)) {
388 prop.setComponentInstanceId(s);
389 prop.setComponentInstanceName(ciName);
397 public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId,
398 final ComponentInstance resourceInstance, final boolean needLock) {
399 final User user = validateUserExists(userId);
400 validateUserNotEmpty(user, "Create component instance");
401 validateJsonBody(resourceInstance, ComponentInstance.class);
402 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
403 final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
404 if (ModelConverter.isAtomicComponent(containerComponent)) {
405 if (log.isDebugEnabled()) {
406 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
408 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
410 validateCanWorkOnComponent(containerComponent, userId);
411 Component origComponent = null;
412 if (resourceInstance != null && containerComponentType != null) {
413 final OriginTypeEnum originType = resourceInstance.getOriginType();
414 validateInstanceName(resourceInstance);
415 if (originType == OriginTypeEnum.ServiceProxy) {
416 origComponent = getOrigComponentForServiceProxy(containerComponent, resourceInstance);
417 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
418 origComponent = getOrigComponentForServiceSubstitution(resourceInstance);
420 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
421 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
423 validateResourceInstanceState(containerComponent, origComponent);
424 overrideFields(origComponent, resourceInstance);
425 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
427 return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
430 private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) {
431 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
432 if (isServiceProxyOrigin(serviceProxyOrigin)) {
433 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
435 Component origComponent = serviceProxyOrigin.left().value();
436 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
437 if (isFillProxyRes(fillProxyRes)) {
438 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
440 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, OriginTypeEnum.ServiceProxy);
441 return origComponent;
444 private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) {
445 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
446 .getToscaFullElement(resourceInstance.getComponentUid());
447 if (getServiceResult.isRight()) {
448 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
450 final Component service = getServiceResult.left().value();
451 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
452 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
453 if (getServiceDerivedFromTypeResult.isRight()) {
454 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
456 Component origComponent = getServiceDerivedFromTypeResult.left().value();
457 final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
458 if (isFillProxyRes(fillProxyRes)) {
459 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
461 return origComponent;
464 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent,
465 ComponentInstance resourceInstance, User user) {
466 boolean failed = false;
468 lockIfNeed(needLock, containerComponent);
469 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
470 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
471 } catch (ComponentException e) {
476 unlockComponent(failed, containerComponent);
482 * Try using either to make a judgment
484 * @param containerComponentParam
485 * @param containerComponentId
487 * @param resourceInstance
490 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
491 String userId, ComponentInstance resourceInstance) {
492 log.debug("enter createRealComponentInstance");
493 return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
497 * Try using either to make a judgment
500 * @param containerComponentParam
501 * @param containerComponentId
503 * @param resourceInstance
506 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
507 String userId, ComponentInstance resourceInstance,
509 log.debug("enter createRealComponentInstance");
510 Component origComponent = null;
512 org.openecomp.sdc.be.model.Component containerComponent = null;
513 ComponentTypeEnum containerComponentType;
515 user = validateUserExists(userId);
516 validateUserNotEmpty(user, "Create component instance");
517 validateJsonBody(resourceInstance, ComponentInstance.class);
518 containerComponentType = validateComponentType(containerComponentParam);
519 containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
520 log.debug("enter createRealComponentInstance,validate user json success");
521 if (ModelConverter.isAtomicComponent(containerComponent)) {
522 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
523 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
525 validateCanWorkOnComponent(containerComponent, userId);
526 log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success");
527 if (resourceInstance != null && containerComponentType != null) {
528 log.debug("enter createRealComponentInstance,start create ComponentInstance");
529 OriginTypeEnum originType = resourceInstance.getOriginType();
530 validateInstanceName(resourceInstance);
531 if (originType == OriginTypeEnum.ServiceProxy) {
532 log.debug("enter createRealComponentInstance,originType equals ServiceProxy");
533 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
534 if (isServiceProxyOrigin(serviceProxyOrigin)) {
535 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
537 origComponent = serviceProxyOrigin.left().value();
538 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
539 if (isFillProxyRes(fillProxyRes)) {
540 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
543 log.debug("enter createRealComponentInstance,originType is not ServiceProxy");
544 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
546 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
547 validateResourceInstanceState(containerComponent, origComponent);
548 overrideFields(origComponent, resourceInstance);
549 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
550 log.debug("enter createRealComponentInstance,final validate success");
552 return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user);
553 } catch (ComponentException e) {
554 log.debug("create Real Component Instance failed");
559 private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent,
560 ComponentInstance resourceInstance, User user) {
561 log.debug("enter createRealComponent");
562 boolean failed = false;
564 lockIfNeed(needLock, containerComponent);
565 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
566 return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
567 } catch (ComponentException e) {
572 unlockComponent(failed, containerComponent);
577 private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent,
578 Component originComponent,
579 ComponentInstance componentInstance, User user) {
580 log.debug("enter createRealComponentInstanceOnGraph");
581 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
582 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
583 if (result.isRight()) {
584 log.debug("enter createRealComponentInstanceOnGraph,result is right");
585 ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value());
586 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
587 return Either.right(componentsUtils.getResponseFormat(status));
589 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
590 log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created.");
591 Component updatedComponent = result.left().value().getLeft();
592 Map<String, String> existingEnvVersions = new HashMap<>();
593 // TODO existingEnvVersions ??
594 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
595 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
596 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
597 if (!updatedInstanceOptional.isPresent()) {
598 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
599 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
601 log.debug("enter createRealComponentInstanceOnGraph,and final success");
602 return Either.left(updatedInstanceOptional.get());
605 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
606 resourceInstance.setComponentVersion(origComponent.getVersion());
607 resourceInstance.setIcon(origComponent.getIcon());
610 private void validateInstanceName(ComponentInstance resourceInstance) {
611 String resourceInstanceName = resourceInstance.getName();
612 if (StringUtils.isEmpty(resourceInstanceName)) {
613 log.debug("ComponentInstance name is empty");
614 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
616 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
617 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
618 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
620 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
621 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
622 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
626 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
627 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
628 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
629 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
633 private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent,
634 final OriginTypeEnum originType) {
635 final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
636 validateOriginType(originType, resourceType);
637 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
640 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
641 switch (containerComponent.getComponentType()) {
643 if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType, containerComponent.getModel())) {
644 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
645 containerComponent.getComponentType().toString(), resourceType.name());
649 final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
650 if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
651 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
652 containerComponent.getComponentType().toString(), resourceType.name());
656 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
660 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
661 ResourceTypeEnum convertedOriginType;
663 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
664 } catch (Exception e) {
665 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
667 if (resourceType != convertedOriginType) {
668 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
672 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
673 switch (origComponent.getComponentType()) {
675 return ResourceTypeEnum.ServiceProxy;
677 return ((Resource) origComponent).getResourceType();
679 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
683 private void lockIfNeed(boolean needLock, Component containerComponent) {
685 lockComponent(containerComponent, "createComponentInstance");
689 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
690 if (serviceProxyOrigin.isRight()) {
691 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
697 private StorageOperationStatus fillInstanceData(ComponentInstance resourceInstance, Component origComponent) {
698 final ComponentParametersView filter = new ComponentParametersView(true);
699 filter.setIgnoreCapabilities(false);
700 filter.setIgnoreCapabiltyProperties(false);
701 filter.setIgnoreComponentInstances(false);
702 filter.setIgnoreRequirements(false);
703 filter.setIgnoreInterfaces(false);
704 filter.setIgnoreProperties(false);
705 filter.setIgnoreAttributes(false);
706 filter.setIgnoreInputs(false);
707 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
708 if (serviceRes.isRight()) {
709 return serviceRes.right().value();
711 final Component service = serviceRes.left().value();
712 final Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
713 resourceInstance.setCapabilities(capabilities);
714 final Map<String, List<RequirementDefinition>> req = service.getRequirements();
715 resourceInstance.setRequirements(req);
716 final Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
717 if (MapUtils.isNotEmpty(serviceInterfaces)) {
718 serviceInterfaces.forEach(resourceInstance::addInterface);
720 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
721 resourceInstance.setAttributes(service.getAttributes());
722 final List<InputDefinition> serviceInputs = service.getInputs();
723 resourceInstance.setInputs(serviceInputs);
724 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
725 resourceInstance.setSourceModelName(service.getName());
726 resourceInstance.setSourceModelUuid(service.getUUID());
727 resourceInstance.setSourceModelUid(service.getUniqueId());
728 resourceInstance.setComponentUid(origComponent.getUniqueId());
729 resourceInstance.setComponentVersion(service.getVersion());
730 switch (resourceInstance.getOriginType()) {
732 return fillProxyInstanceData(resourceInstance, origComponent, service);
733 case ServiceSubstitution:
734 return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
736 return StorageOperationStatus.OK;
740 private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent,
741 final Component service) {
742 final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
743 final String toscaResourceName = ((Resource) origComponent).getToscaResourceName();
744 final int lastIndexOf = toscaResourceName.lastIndexOf('.');
745 if (lastIndexOf != -1) {
746 final String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
747 resourceInstance.setToscaComponentName(proxyToscaName);
749 resourceInstance.setName(name);
750 resourceInstance.setIsProxy(true);
751 resourceInstance.setDescription("A Proxy for Service " + service.getName());
752 return StorageOperationStatus.OK;
755 private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) {
756 resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
757 resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName()));
758 resourceInstance.setIsProxy(false);
759 resourceInstance.setDescription("A substitutable node type for service " + service.getName());
760 return StorageOperationStatus.OK;
763 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId,
764 String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
765 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
766 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
767 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
768 User user = validateUserExists(userId);
769 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
770 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
771 if (ModelConverter.isAtomicComponent(containerComponent)) {
772 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
774 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
776 validateCanWorkOnComponent(containerComponent, userId);
777 boolean failed = false;
779 lockComponent(containerComponent, "createAndAssociateRIToRI");
780 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
781 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
782 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
783 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
784 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
785 associationInfo.setFromNode(resResourceInfo.getUniqueId());
787 associationInfo.setToNode(resResourceInfo.getUniqueId());
789 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade
790 .associateResourceInstances(containerComponent, containerComponentId, associationInfo);
791 if (resultReqCapDef.isLeft()) {
792 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
793 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
794 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
795 resultOp = Either.left(resInfo);
798 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
799 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(
800 componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
803 } catch (ComponentException e) {
807 unlockComponent(failed, containerComponent);
811 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
812 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
815 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
816 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
819 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
820 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
821 if (eitherComponent.isRight()) {
822 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
823 throw new ByActionStatusComponentException(
824 componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
826 return eitherComponent.left().value();
829 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent,
830 ComponentInstance componentInstance, User user) {
831 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
832 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
833 if (result.isRight()) {
834 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
835 throw new ByResponseFormatComponentException(componentsUtils
836 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "",
839 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
840 Component updatedComponent = result.left().value().getLeft();
841 Map<String, String> existingEnvVersions = new HashMap<>();
842 // TODO existingEnvVersions ??
843 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
844 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
845 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
846 if (!updatedInstanceOptional.isPresent()) {
847 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
848 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
850 return updatedInstanceOptional.get();
853 public boolean isCloudSpecificArtifact(String artifact) {
854 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
855 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
856 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
867 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's
870 * @param containerComponent
871 * @param componentInstance
872 * @param originComponent
874 * @param existingEnvVersions
877 protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance,
878 org.openecomp.sdc.be.model.Component originComponent, User user,
879 Map<String, String> existingEnvVersions) {
880 log.debug("add artifacts to resource instance");
881 List<GroupDefinition> filteredGroups = new ArrayList<>();
882 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
883 if (ActionStatus.OK != status) {
884 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
886 StorageOperationStatus artStatus;
887 // generate heat_env if necessary
888 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
889 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
890 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
891 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
892 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
893 .getDefaultMinutes();
894 List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
895 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
896 String type = artifact.getArtifactType();
897 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
898 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
900 if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type
901 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type
902 .equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
903 artifact.setTimeout(defaultHeatTimeout);
907 if (artifact.checkEsIdExist()) {
908 ArtifactDefinition artifactDefinition = artifactBusinessLogic
909 .createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
910 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions);
912 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
913 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
914 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
916 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
917 listOfCloudSpecificArts.add(artifact);
919 if (CollectionUtils.isNotEmpty(filteredGroups)) {
920 filteredGroups.stream()
921 .filter(g -> g.getArtifacts() != null && g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst()
922 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
926 groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts));
927 filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> {
928 g.getArtifactsUuid().add(e.getArtifactUUID());
929 g.getArtifacts().add(e.getUniqueId());
931 artStatus = toscaOperationFacade
932 .addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
933 if (artStatus != StorageOperationStatus.OK) {
934 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(),
935 containerComponent.getUniqueId(), artStatus);
936 throw new ByResponseFormatComponentException(
937 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
939 StorageOperationStatus result = toscaOperationFacade
940 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
941 if (result != StorageOperationStatus.OK) {
942 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
943 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
945 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
947 artStatus = toscaOperationFacade
948 .addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
949 if (artStatus != StorageOperationStatus.OK) {
950 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}",
951 componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
952 throw new ByResponseFormatComponentException(
953 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
955 componentInstance.setArtifacts(originComponent.getArtifacts());
956 return ActionStatus.OK;
959 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition,
960 GroupDefinition groupInstance) {
961 List<ArtifactDefinition> artifactsUid;
962 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
963 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
965 artifactsUid = new ArrayList<>();
967 artifactsUid.add(artifactDefinition);
968 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
971 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
972 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic
973 .getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
974 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
975 if (getResourceDeploymentArtifacts.isRight()) {
976 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
977 if (status != StorageOperationStatus.NOT_FOUND) {
978 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
979 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
982 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
984 if (!deploymentArtifacts.isEmpty()) {
985 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
986 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
987 if (!artifact.getValue().checkEsIdExist()) {
988 tempDeploymentArtifacts.remove(artifact.getKey());
991 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
993 return ActionStatus.OK;
996 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId,
997 String componentInstanceId, String userId,
998 ComponentInstance componentInstance) {
999 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true);
1002 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(final String containerComponentParam,
1003 final String containerComponentId,
1004 final String componentInstanceId, final String userId,
1005 ComponentInstance componentInstance, boolean needLock) {
1006 validateUserExists(userId);
1007 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1008 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1009 validateCanWorkOnComponent(containerComponent, userId);
1010 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1011 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade
1012 .validateComponentExists(componentInstance.getComponentUid());
1013 if (validateParentStatus.isRight()) {
1014 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
1015 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(),
1016 instanceType.getValue().toLowerCase());
1018 if (!Boolean.TRUE.equals(validateParentStatus.left().value())) {
1019 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1020 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1023 lockComponent(containerComponent, "updateComponentInstance");
1025 Component origComponent;
1026 boolean failed = false;
1028 origComponent = getOriginComponentFromComponentInstance(componentInstance);
1029 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId,
1031 } catch (ComponentException e) {
1036 unlockComponent(failed, containerComponent);
1039 return Either.left(componentInstance);
1042 // New Multiple Instance Update API
1043 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId,
1044 String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
1045 boolean failed = false;
1047 validateUserExists(userId);
1048 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1049 ComponentParametersView componentFilter = new ComponentParametersView();
1050 componentFilter.disableAll();
1051 componentFilter.setIgnoreUsers(false);
1052 componentFilter.setIgnoreComponentInstances(false);
1053 if (containerComponent == null) {
1054 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
1056 validateCanWorkOnComponent(containerComponent, userId);
1057 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1058 for (ComponentInstance componentInstance : componentInstanceList) {
1059 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
1060 if (!validateParent) {
1061 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1062 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1066 lockComponent(containerComponent, "updateComponentInstance");
1068 List<ComponentInstance> updatedList = new ArrayList<>();
1069 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
1070 List<ComponentInstance> listForUpdate = new ArrayList<>();
1071 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) {
1072 containerComponent.setComponentInstances(componentInstanceList);
1074 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
1075 while (iterator.hasNext()) {
1076 ComponentInstance origInst = iterator.next();
1077 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId()))
1079 if (op.isPresent()) {
1080 ComponentInstance updatedCi = op.get();
1081 updatedCi = buildComponentInstance(updatedCi, origInst);
1082 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
1083 if (!Boolean.TRUE.equals(isUniqueName)) {
1084 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1085 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1086 origInst.getName(), updatedCi.getName());
1087 throw new ByResponseFormatComponentException(componentsUtils
1088 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
1090 listForUpdate.add(updatedCi);
1092 listForUpdate.add(origInst);
1095 containerComponent.setComponentInstances(listForUpdate);
1096 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade
1097 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
1098 if (updateStatus.isRight()) {
1100 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ",
1101 containerComponent.getName(), updateStatus.right().value());
1102 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
1103 componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
1105 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
1106 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName()))
1108 if (op.isPresent()) {
1109 updatedList.add(updatedInstance);
1114 } catch (ComponentException e) {
1119 unlockComponent(failed, containerComponent);
1124 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
1125 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
1128 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
1129 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
1130 return ComponentTypeEnum.SERVICE_INSTANCE;
1132 return ComponentTypeEnum.RESOURCE_INSTANCE;
1136 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType,
1137 org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
1138 ComponentInstance componentInstance) {
1139 Optional<ComponentInstance> componentInstanceOptional;
1140 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
1141 ComponentInstance oldComponentInstance = null;
1142 boolean isNameChanged = false;
1143 componentInstanceOptional = containerComponent.getComponentInstances().stream()
1144 .filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
1145 if (!componentInstanceOptional.isPresent()) {
1146 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ",
1147 componentInstance.getName(), containerComponent.getName());
1148 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
1150 String oldComponentName;
1151 oldComponentInstance = componentInstanceOptional.get();
1152 oldComponentName = oldComponentInstance.getName();
1153 String newInstanceName = componentInstance.getName();
1154 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) {
1155 isNameChanged = true;
1157 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
1158 if (!Boolean.TRUE.equals(isUniqueName)) {
1159 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1160 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1161 oldComponentInstance.getName(), newInstanceName);
1162 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(),
1163 componentInstance.getName());
1165 if (!DirectivesUtil.isValid(componentInstance.getDirectives())) {
1166 final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
1167 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1168 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(),
1169 newInstanceName, directivesStr);
1170 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(),
1171 componentInstance.getName());
1173 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent,
1174 updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
1175 if (updateRes.isRight()) {
1176 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1177 "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(),
1178 containerComponent.getName(), updateRes.right().value());
1179 throw new ByResponseFormatComponentException(componentsUtils
1180 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true),
1183 // region - Update instance Groups
1184 if (isNameChanged) {
1185 Either<StorageOperationStatus, StorageOperationStatus> result = toscaOperationFacade
1186 .cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
1187 if (result.isRight()) {
1189 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId,
1190 result.right().value());
1192 if (containerComponent instanceof Service) {
1193 Either<ComponentInstance, ResponseFormat> renameEither = renameServiceFilter((Service) containerComponent, newInstanceName,
1194 oldComponentInstance.getName());
1195 if (renameEither.isRight()) {
1196 throw new ByResponseFormatComponentException(renameEither.right().value());
1198 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
1203 String newInstanceId = updateRes.left().value().getRight();
1204 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream()
1205 .filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
1206 if (!updatedInstanceOptional.isPresent()) {
1207 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(),
1208 containerComponent.getName());
1209 throw new ByResponseFormatComponentException(
1210 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
1212 return componentInstanceOptional.get();
1215 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
1216 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
1217 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
1218 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName());
1219 updated.forEach(fp -> {
1220 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
1221 .updateForwardingPath(containerComponent.getUniqueId(), fp);
1222 if (resultEither.isRight()) {
1223 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",
1224 containerComponent.getName(), resultEither.right().value());
1229 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent, final String newInstanceName,
1230 final String oldInstanceName) {
1231 Map<String, CINodeFilterDataDefinition> renamedNodesFilter = ServiceFilterUtils
1232 .getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
1233 for (Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()) {
1234 Either<CINodeFilterDataDefinition, StorageOperationStatus> renameEither = nodeFilterOperation
1235 .updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue());
1236 if (renameEither.isRight()) {
1237 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1238 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(),
1242 return Either.left(null);
1246 * @param oldPrefix- The normalized old vf name
1247 * @param newNormailzedPrefix- The normalized new vf name
1248 * @param qualifiedGroupInstanceName- old Group Instance Name
1251 // modify group names
1252 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1253 if (qualifiedGroupInstanceName == null) {
1254 log.info("CANNOT change group name ");
1257 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName
1258 .startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) {
1259 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1261 return qualifiedGroupInstanceName;
1264 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1265 oldComponentInstance.setName(newComponentInstance.getName());
1266 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1267 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1268 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1269 oldComponentInstance.setMaxOccurrences(newComponentInstance.getMaxOccurrences());
1270 oldComponentInstance.setMinOccurrences(newComponentInstance.getMinOccurrences());
1271 oldComponentInstance.setInstanceCount(newComponentInstance.getInstanceCount());
1272 if (oldComponentInstance.getGroupInstances() != null) {
1273 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(),
1274 ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1276 return oldComponentInstance;
1279 public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId,
1280 final String componentInstanceId, String userId) throws BusinessLogicException {
1281 validateUserExists(userId);
1282 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1283 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1284 validateCanWorkOnComponent(containerComponent, userId);
1285 boolean failed = false;
1286 final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1287 if (!componentInstanceOptional.isPresent()) {
1288 throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
1290 ComponentInstance componentInstance = componentInstanceOptional.get();
1292 if (containerComponent instanceof Service || containerComponent instanceof Resource) {
1293 final Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1294 .deleteNodeFilter(containerComponent, componentInstanceId);
1295 if (deleteServiceFilterEither.isRight()) {
1296 final ActionStatus status = componentsUtils
1297 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1298 janusGraphDao.rollback();
1299 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1301 final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
1302 componentInstance, containerComponentType, userId);
1303 if (resultOp.isRight()) {
1304 janusGraphDao.rollback();
1305 throw new ByResponseFormatComponentException(resultOp.right().value());
1308 lockComponent(containerComponent, "deleteComponentInstance");
1309 final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1310 componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1311 deletedCompInstance);
1312 final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1313 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1314 if (ActionStatus.OK != onDeleteOperationsStatus) {
1315 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1317 } catch (final ComponentException e) {
1321 unlockComponent(failed, containerComponent);
1323 return componentInstance;
1327 * Try to modify the delete and return two cases
1329 * @param containerComponentParam
1330 * @param containerComponentId
1331 * @param componentInstanceId
1335 public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId,
1336 String componentInstanceId, String userId) {
1337 log.debug("enter deleteAbstractComponentInstance");
1338 validateUserExists(userId);
1339 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1340 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1341 validateCanWorkOnComponent(containerComponent, userId);
1342 boolean failed = false;
1343 ComponentInstance deletedRelatedInst;
1345 if (containerComponent instanceof Service) {
1346 final Optional<ComponentInstance> componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId);
1347 if (componentInstanceById.isPresent()) {
1348 ComponentInstance componentInstance = componentInstanceById.get();
1349 Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1350 .deleteNodeFilter(containerComponent, componentInstanceId);
1351 if (deleteServiceFilterEither.isRight()) {
1352 log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed");
1353 ActionStatus status = componentsUtils
1354 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1355 janusGraphDao.rollback();
1356 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1358 Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance,
1359 ComponentTypeEnum.SERVICE, userId);
1360 if (resultOp.isRight()) {
1361 log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed");
1362 janusGraphDao.rollback();
1367 log.debug("enter deleteAbstractComponentInstance:");
1368 lockComponent(containerComponent, "deleteComponentInstance");
1369 ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1370 deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1371 deletedCompInstance);
1372 ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1373 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1374 log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus);
1375 if (ActionStatus.OK != onDeleteOperationsStatus) {
1376 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1378 } catch (ComponentException e) {
1382 unlockComponent(failed, containerComponent);
1384 log.debug("enter deleteAbstractComponentInstance,deleted RelatedInst success");
1385 return Either.left(deletedRelatedInst);
1388 public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(final Component component,
1389 final ComponentInstance componentInstance,
1390 final ComponentTypeEnum containerComponentType,
1391 final String userId) {
1392 final Set<String> componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
1393 if (!componentFiltersIDsToBeDeleted.isEmpty()) {
1394 final Set<String> ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
1395 .map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
1396 final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation
1397 .deleteNodeFilters(component, ids);
1398 if (deleteComponentNodeFiltersEither.isRight()) {
1399 final ActionStatus status = componentsUtils
1400 .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType);
1401 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1403 for (final String id : ids) {
1404 final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id);
1405 if (!componentInstanceById.isPresent()) {
1406 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1408 final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
1409 componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
1410 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(
1411 containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId,
1412 componentInstanceToBeUpdated, false);
1413 if (componentInstanceResponseFormatEither.isRight()) {
1414 return componentInstanceResponseFormatEither;
1418 return Either.left(componentInstance);
1421 private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) {
1422 ComponentParametersView filter = new ComponentParametersView(true);
1423 filter.setIgnoreComponentInstances(false);
1424 Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1425 final Component component = componentFilterOrigin.left().value();
1426 return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance);
1429 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
1430 ComponentInstance componentInstance) {
1431 if (containerComponentType == ComponentTypeEnum.SERVICE) {
1432 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1433 if (!pathIDsToBeDeleted.isEmpty()) {
1434 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1437 return componentInstance;
1440 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete) {
1441 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1442 if (storageStatus.isRight()) {
1443 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1445 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation
1446 .deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete));
1447 if (result.isRight()) {
1448 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1452 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) {
1453 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1454 List<String> pathIDsToBeDeleted = new ArrayList<>();
1455 allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId))
1456 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1457 return pathIDsToBeDeleted;
1460 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1461 ComponentParametersView filter = new ComponentParametersView(true);
1462 filter.setIgnoreServicePath(false);
1463 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1464 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1467 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) {
1468 return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch(
1469 elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode()
1470 .equalsIgnoreCase(componentInstanceId));
1473 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId,
1474 ComponentTypeEnum containerComponentType) {
1475 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade
1476 .deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1477 if (deleteRes.isRight()) {
1478 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1479 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1480 throw new ByActionStatusComponentException(status, componentInstanceId);
1482 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1483 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1484 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1485 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream()
1486 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1487 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1488 StorageOperationStatus deleteInputsRes = toscaOperationFacade
1489 .deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1490 if (deleteInputsRes != StorageOperationStatus.OK) {
1491 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1492 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType),
1493 componentInstanceId);
1497 if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) {
1498 final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream()
1499 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1500 if (CollectionUtils.isNotEmpty(outputsToDelete)) {
1501 final StorageOperationStatus deleteOutputsRes = toscaOperationFacade
1502 .deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
1503 if (deleteOutputsRes != StorageOperationStatus.OK) {
1504 log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId);
1505 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType),
1506 componentInstanceId);
1510 return deletedInstance;
1513 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1514 ComponentInstance foundInstance = null;
1515 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1516 if (instance.getUniqueId().equals(componentInstanceId)) {
1517 foundInstance = instance;
1518 containerComponent.getComponentInstances().remove(instance);
1522 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1523 return foundInstance;
1526 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1527 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) {
1528 containerComponent.setComponentInstancesRelations(
1529 containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r))
1530 .collect(Collectors.toList()));
1534 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1535 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1538 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1539 ComponentTypeEnum componentTypeEnum) {
1540 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true);
1543 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1544 ComponentTypeEnum componentTypeEnum, boolean needLock) {
1545 validateUserExists(userId);
1546 RequirementCapabilityRelDef requirementCapabilityRelDef;
1547 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1548 validateCanWorkOnComponent(containerComponent, userId);
1549 boolean failed = false;
1552 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1554 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1555 } catch (ComponentException e) {
1560 unlockComponent(failed, containerComponent);
1563 return requirementCapabilityRelDef;
1566 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1567 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1568 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1569 .associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1570 if (result.isLeft()) {
1571 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1572 return result.left().value();
1574 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1575 String fromNameOrId = "";
1576 String toNameOrId = "";
1577 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1578 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1579 toNameOrId = requirementDef.getFromNode();
1580 fromNameOrId = requirementDef.getFromNode();
1581 if (fromResult.isLeft()) {
1582 fromNameOrId = fromResult.left().value().getName();
1584 if (toResult.isLeft()) {
1585 toNameOrId = toResult.left().value().getName();
1587 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1588 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1593 * @param componentId
1595 * @param requirementDefList
1596 * @param componentTypeEnum
1599 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(String componentId, String userId,
1600 List<RequirementCapabilityRelDef> requirementDefList,
1601 ComponentTypeEnum componentTypeEnum) {
1602 validateUserExists(userId);
1603 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1604 validateCanWorkOnComponent(containerComponent, userId);
1605 boolean failed = false;
1606 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1608 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1609 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1610 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef,
1611 containerComponent.getComponentType());
1612 delOkResult.add(requirementCapabilityRelDef);
1614 } catch (ComponentException e) {
1618 unlockComponent(failed, containerComponent);
1623 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1624 ComponentTypeEnum componentTypeEnum) {
1625 validateUserExists(userId);
1626 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1627 validateCanWorkOnComponent(containerComponent, userId);
1628 boolean failed = false;
1630 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1631 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1632 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1633 .dissociateResourceInstances(componentId, requirementDef);
1634 if (result.isLeft()) {
1635 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1636 return result.left().value();
1638 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1639 String fromNameOrId = "";
1640 String toNameOrId = "";
1641 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent,
1642 requirementDef.getFromNode());
1643 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1644 toNameOrId = requirementDef.getFromNode();
1645 fromNameOrId = requirementDef.getFromNode();
1646 if (fromResult.isLeft()) {
1647 fromNameOrId = fromResult.left().value().getName();
1649 if (toResult.isLeft()) {
1650 toNameOrId = toResult.left().value().getName();
1652 throw new ByActionStatusComponentException(
1653 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId,
1654 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1656 } catch (ComponentException e) {
1660 unlockComponent(failed, containerComponent);
1665 * Allows to get relation contained in specified component according to received Id
1667 * @param componentId
1670 * @param componentTypeEnum
1673 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId,
1674 ComponentTypeEnum componentTypeEnum) {
1675 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1677 org.openecomp.sdc.be.model.Component containerComponent = null;
1678 RequirementCapabilityRelDef foundRelation = null;
1679 validateUserExists(userId);
1680 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1681 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1682 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1683 if (foundRelation == null) {
1684 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1685 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1686 resultOp = Either.right(responseFormat);
1688 if (resultOp == null) {
1689 resultOp = setRelatedCapability(foundRelation, containerComponent);
1691 if (resultOp.isLeft()) {
1692 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1694 } catch (Exception e) {
1695 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1696 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1701 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1702 for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) {
1703 if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) {
1704 return relationship;
1710 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation,
1711 Component containerComponent) {
1712 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1713 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1714 String instanceId = foundRelation.getFromNode();
1715 Optional<RequirementDefinition> foundRequirement;
1716 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1718 if (!instance.isPresent()) {
1719 ResponseFormat responseFormat = componentsUtils
1720 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1721 containerComponent.getComponentType().getValue(), containerComponent.getName());
1722 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1723 result = Either.right(responseFormat);
1725 if (result == null && instance.isPresent()) {
1726 for (List<RequirementDefinition> requirements : instance.get().getRequirements().values()) {
1727 foundRequirement = requirements.stream()
1728 .filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1729 if (foundRequirement.isPresent()) {
1730 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1731 result = Either.left(foundRelation);
1735 if (result == null) {
1736 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1737 .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1738 if (getfulfilledRequirementRes.isRight()) {
1739 ResponseFormat responseFormat = componentsUtils
1740 .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId,
1741 containerComponent.getUniqueId());
1742 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1743 containerComponent.getUniqueId());
1744 result = Either.right(responseFormat);
1746 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1749 if (result == null) {
1750 result = Either.left(foundRelation);
1755 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1756 return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req
1757 .getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1760 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1761 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId()
1762 .equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1765 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation,
1766 Component containerComponent) {
1767 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1768 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1769 String instanceId = foundRelation.getToNode();
1770 Optional<CapabilityDefinition> foundCapability;
1771 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1773 if (!instance.isPresent()) {
1774 ResponseFormat responseFormat = componentsUtils
1775 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1776 containerComponent.getComponentType().getValue(), containerComponent.getName());
1777 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1778 result = Either.right(responseFormat);
1780 if (result == null && instance.isPresent()) {
1781 for (List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()) {
1782 foundCapability = capabilities.stream()
1783 .filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1784 if (foundCapability.isPresent()) {
1785 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1786 result = Either.left(foundRelation);
1790 if (result == null) {
1791 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1792 .getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1793 if (getfulfilledRequirementRes.isRight()) {
1794 ResponseFormat responseFormat = componentsUtils
1795 .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId,
1796 containerComponent.getUniqueId());
1797 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1798 containerComponent.getUniqueId());
1799 result = Either.right(responseFormat);
1801 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1804 if (result == null) {
1805 result = Either.left(foundRelation);
1810 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1811 return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap
1812 .getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1815 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1816 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId()
1817 .equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1820 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1821 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship)
1822 : previousName != null && previousName.equals(nameFromRelationship);
1825 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1826 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1827 .updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1828 Either<ComponentInstanceProperty, ResponseFormat> result;
1829 if (eitherAttribute.isLeft()) {
1830 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1831 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1832 result = Either.left(instanceAttribute);
1834 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1835 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1836 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1841 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1842 Either<ComponentInstanceProperty, ResponseFormat> result;
1843 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1844 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1845 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1846 if (!errorWrapper.isEmpty()) {
1847 result = Either.right(errorWrapper.getInnerElement());
1849 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1850 .addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1851 if (eitherAttribute.isLeft()) {
1852 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1853 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1854 result = Either.left(instanceAttribute);
1856 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1857 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1858 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1865 * Create Or Updates Attribute Instance
1867 * @param componentTypeEnum
1868 * @param componentId
1869 * @param resourceInstanceId
1874 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId,
1875 String resourceInstanceId,
1876 ComponentInstanceProperty attribute, String userId) {
1877 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1878 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1879 validateUserExists(userId);
1880 if (errorWrapper.isEmpty()) {
1881 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1883 if (errorWrapper.isEmpty()) {
1884 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1886 if (errorWrapper.isEmpty()) {
1887 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1890 if (errorWrapper.isEmpty()) {
1891 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1893 result = createAttributeValue(attribute, resourceInstanceId);
1895 result = updateAttributeValue(attribute, resourceInstanceId);
1898 result = Either.right(errorWrapper.getInnerElement());
1902 if (result == null || result.isRight()) {
1903 janusGraphDao.rollback();
1905 janusGraphDao.commit();
1908 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1912 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum,
1913 String componentId, String resourceInstanceId,
1914 List<ComponentInstanceProperty> properties,
1916 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1917 /*-------------------------------Validations---------------------------------*/
1918 validateUserExists(userId);
1920 if (componentTypeEnum == null) {
1921 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1922 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1925 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1927 if (getResourceResult.isRight()) {
1928 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1929 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1930 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1932 Component containerComponent = getResourceResult.left().value();
1934 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1935 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
1936 log.info(COMPONENT_ARCHIVED, componentId);
1937 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1939 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
1940 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1943 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1944 if (resourceInstanceStatus.isRight()) {
1945 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1946 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
1948 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1951 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1952 if (lockStatus != StorageOperationStatus.OK) {
1953 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1954 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1956 List<ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1958 for (ComponentInstanceProperty property : properties) {
1959 validateMandatoryFields(property);
1960 ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent,
1961 foundResourceInstance);
1962 String propertyParentUniqueId = property.getParentUniqueId();
1963 if (property.isGetFunction()) {
1964 validateToscaGetFunction(property, containerComponent);
1965 property.setValue(property.getToscaGetFunction().generatePropertyValue());
1967 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, containerComponent.getModel());
1968 if (updatedPropertyValue.isRight()) {
1969 log.error("Failed to update property object value of property: {}",
1971 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1973 Optional<CapabilityDefinition>
1974 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1975 if (capPropDefinition.isPresent()) {
1976 updatedPropertyValue
1977 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1978 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1979 capPropDefinition.get().getName()), Either::right);
1981 updatedPropertyValue.bimap(
1983 componentInstanceProperty.setValue(updatedValue);
1984 return updatePropertyOnContainerComponent(property, updatedValue,
1985 containerComponent, foundResourceInstance);
1987 updatedProperties.add(componentInstanceProperty);
1991 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
1992 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1993 if (updateContainerRes.isRight()) {
1994 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1995 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1998 resultOp = Either.left(updatedProperties);
2001 } catch (final ComponentException e) {
2002 return Either.right(e.getResponseFormat());
2004 if (resultOp == null || resultOp.isRight()) {
2005 janusGraphDao.rollback();
2007 janusGraphDao.commit();
2010 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2014 public Either<List<ComponentInstanceAttribute>, ResponseFormat> createOrUpdateAttributeValues(final ComponentTypeEnum componentTypeEnum,
2015 final String componentId,
2016 final String resourceInstanceId,
2017 final List<ComponentInstanceAttribute> attributes,
2018 final String userId) {
2019 Either<List<ComponentInstanceAttribute>, ResponseFormat> resultOp = null;
2020 /*-------------------------------Validations---------------------------------*/
2021 validateUserExists(userId);
2023 if (componentTypeEnum == null) {
2024 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2025 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2028 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade
2029 .getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2031 if (getResourceResult.isRight()) {
2032 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2033 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2034 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2036 final Component containerComponent = getResourceResult.left().value();
2038 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2039 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2040 log.info(COMPONENT_ARCHIVED, componentId);
2041 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2043 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2044 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2047 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
2048 resourceInstanceId);
2049 if (resourceInstanceStatus.isRight()) {
2050 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2051 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2053 final ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2056 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2057 if (lockStatus != StorageOperationStatus.OK) {
2058 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2059 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2061 final List<ComponentInstanceAttribute> updatedProperties = new ArrayList<>();
2063 for (final ComponentInstanceAttribute attribute : attributes) {
2064 final ComponentInstanceAttribute componentInstanceProperty = validateAttributeExistsOnComponent(attribute, containerComponent,
2065 foundResourceInstance);
2066 final Either<String, ResponseFormat> updatedPropertyValue = updateAttributeObjectValue(attribute);
2067 if (updatedPropertyValue.isRight()) {
2068 log.error("Failed to update attribute object value of attribute: {}", attribute);
2069 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
2071 updatedPropertyValue.bimap(
2073 componentInstanceProperty.setValue(updatedValue);
2074 return updateAttributeOnContainerComponent(attribute, updatedValue,
2075 containerComponent, foundResourceInstance);
2077 updatedProperties.add(componentInstanceProperty);
2080 final Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2081 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2082 if (updateContainerRes.isRight()) {
2083 final ActionStatus actionStatus = componentsUtils
2084 .convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2085 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2088 resultOp = Either.left(updatedProperties);
2091 } catch (final ComponentException e) {
2092 return Either.right(e.getResponseFormat());
2094 if (resultOp == null || resultOp.isRight()) {
2095 janusGraphDao.rollback();
2097 janusGraphDao.commit();
2100 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2104 private void validateMandatoryFields(PropertyDataDefinition property) {
2105 if (StringUtils.isEmpty(property.getName())) {
2106 throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
2110 private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
2111 ComponentInstance foundResourceInstance) {
2112 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
2113 .get(foundResourceInstance.getUniqueId());
2114 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName()))
2116 if (instanceProperty.isEmpty()) {
2117 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
2119 return instanceProperty.get();
2122 private ComponentInstanceAttribute validateAttributeExistsOnComponent(final ComponentInstanceAttribute attribute,
2123 final Component containerComponent,
2124 final ComponentInstance foundResourceInstance) {
2125 final List<ComponentInstanceAttribute> instanceProperties =
2126 containerComponent.getComponentInstancesAttributes().get(foundResourceInstance.getUniqueId());
2127 final Optional<ComponentInstanceAttribute> instanceAttribute =
2128 instanceProperties.stream().filter(p -> p.getName().equals(attribute.getName())).findAny();
2129 if (!instanceAttribute.isPresent()) {
2130 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, attribute.getName());
2132 return instanceAttribute.get();
2135 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
2136 String newValue, Component containerComponent,
2137 ComponentInstance foundResourceInstance,
2138 String capabilityType, String capabilityName) {
2139 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2140 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2141 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2142 if (actionStatus != null) {
2143 return actionStatus;
2146 return componentsUtils.getResponseFormat(ActionStatus.OK);
2149 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
2150 String newValue, Component containerComponent,
2151 ComponentInstance foundResourceInstance,
2152 String capabilityType, String capabilityName) {
2153 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2154 Either<Component, StorageOperationStatus> getComponentRes =
2155 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
2156 if (getComponentRes.isRight()) {
2157 return componentsUtils.getResponseFormat(getComponentRes.right().value());
2160 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2161 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2162 if (actionStatus != null) {
2163 return actionStatus;
2166 return componentsUtils.getResponseFormat(ActionStatus.OK);
2169 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
2170 Component containerComponent,
2171 ComponentInstance foundResourceInstance,
2172 String capabilityType, String capabilityName,
2173 String componentInstanceUniqueId) {
2174 Map<String, List<CapabilityDefinition>> capabilities =
2175 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
2176 List<CapabilityDefinition> capPerType =
2177 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2178 Optional<CapabilityDefinition> cap =
2179 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
2180 if (cap.isPresent()) {
2181 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2182 if (capProperties != null) {
2183 Optional<ComponentInstanceProperty> instanceProperty =
2184 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2185 StorageOperationStatus status;
2186 if (instanceProperty.isPresent()) {
2187 String capKey = ModelConverter
2188 .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
2189 componentInstanceUniqueId, cap.get());
2190 instanceProperty.get().setValue(newValue);
2191 List<String> path = new ArrayList<>();
2192 path.add(componentInstanceUniqueId);
2194 instanceProperty.get().setPath(path);
2195 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
2196 componentInstanceUniqueId, capKey, instanceProperty.get());
2197 if (status != StorageOperationStatus.OK) {
2198 ActionStatus actionStatus =
2199 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2200 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2203 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2210 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
2211 Component containerComponent, ComponentInstance foundResourceInstance) {
2212 StorageOperationStatus status;
2213 instanceProperty.setValue(newValue);
2214 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
2215 if (status != StorageOperationStatus.OK) {
2216 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2217 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2219 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2220 return componentsUtils.getResponseFormat(ActionStatus.OK);
2223 private ResponseFormat updateAttributeOnContainerComponent(final ComponentInstanceAttribute instanceAttribute,
2224 final String newValue,
2225 final Component containerComponent,
2226 final ComponentInstance foundResourceInstance) {
2228 instanceAttribute.setValue(newValue);
2229 final StorageOperationStatus status =
2230 toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), instanceAttribute);
2231 if (status != StorageOperationStatus.OK) {
2232 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2233 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2235 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2236 return componentsUtils.getResponseFormat(ActionStatus.OK);
2239 private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
2240 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, property.getModel());
2241 String propertyType = property.getType();
2242 String innerType = getInnerType(property);
2244 // Specific Update Logic
2245 Either<Object, Boolean> isValid = propertyOperation
2246 .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
2247 if (isValid.isRight()) {
2248 if (!Boolean.TRUE.equals(isValid.right().value())) {
2249 log.error("Invalid value {} of property {} ", newValue, property.getName());
2250 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2253 Object object = isValid.left().value();
2254 if (object != null) {
2255 newValue = object.toString();
2258 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
2259 return Either.right(componentsUtils.getResponseFormat(componentsUtils
2260 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2262 return Either.left(newValue);
2265 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
2266 String innerType, String propertyType) {
2268 ImmutablePair<String, Boolean> pair = propertyOperation
2269 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2270 if (pair.getRight() != null && !pair.getRight()) {
2271 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2278 private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, final String model) {
2279 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, model);
2280 String innerType = null;
2281 String propertyType = property.getType();
2282 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2283 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
2285 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2286 SchemaDefinition schema = property.getSchema();
2287 if (schema == null) {
2288 log.debug("Schema doesn't exists for property of type {}", type);
2290 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2292 PropertyDataDefinition propDef = schema.getProperty();
2293 if (propDef == null) {
2294 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
2296 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2298 innerType = propDef.getType();
2301 // Specific Update Logic
2302 String newValue = property.getValue();
2304 if (property.hasGetFunction()) {
2305 return Either.left(newValue);
2308 Either<Object, Boolean> isValid = propertyOperation
2309 .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
2310 if (isValid.isRight()) {
2311 if (!Boolean.TRUE.equals(isValid.right().value())) {
2312 log.debug("validate and update property value has failed with value: {}", property.getValue());
2313 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2314 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2317 Object object = isValid.left().value();
2318 if (object != null) {
2319 newValue = object.toString();
2322 ImmutablePair<String, Boolean> pair = propertyOperation
2323 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2324 if (pair.getRight() != null && Boolean.FALSE.equals(pair.getRight())) {
2325 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2326 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2327 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2329 return Either.left(newValue);
2332 private <T extends AttributeDefinition> Either<String, ResponseFormat> updateAttributeObjectValue(final T attribute) {
2333 String innerType = null;
2334 final String attributeType = attribute.getType();
2335 final ToscaPropertyType type = ToscaPropertyType.isValidType(attributeType);
2336 log.debug("The type of the attribute {} is {}", attribute.getUniqueId(), attributeType);
2338 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2339 final SchemaDefinition def = attribute.getSchema();
2341 log.debug("Schema doesn't exists for attribute of type {}", type);
2343 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2345 PropertyDataDefinition propDef = def.getProperty();
2346 if (propDef == null) {
2347 log.debug("Property in Schema Definition inside attribute of type {} doesn't exist", type);
2349 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2351 innerType = propDef.getType();
2354 // Specific Update Logic
2355 String newValue = attribute.getValue();
2357 final var isValid = attributeOperation.validateAndUpdateAttributeValue(attribute, innerType,
2358 componentsUtils.getAllDataTypes(applicationDataTypeCache, attribute.getModel()));
2359 if (isValid.isRight()) {
2360 final Boolean res = isValid.right().value();
2361 if (!Boolean.TRUE.equals(res)) {
2362 log.debug("validate and update attribute value has failed with value: {}", newValue);
2363 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2364 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2367 final Object object = isValid.left().value();
2368 if (object != null) {
2369 newValue = object.toString();
2372 return Either.left(newValue);
2375 private <T extends PropertyDefinition> void validateToscaGetFunction(T property, Component parentComponent) {
2376 final ToscaGetFunctionDataDefinition toscaGetFunction = property.getToscaGetFunction();
2377 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_INPUT) {
2378 validateGetFunction(property, parentComponent.getInputs(), parentComponent.getModel());
2381 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_PROPERTY) {
2382 validateGetFunction(property, parentComponent.getProperties(), parentComponent.getModel());
2386 throw ToscaGetFunctionExceptionSupplier.functionNotSupported(toscaGetFunction.getFunctionType()).get();
2389 private <T extends PropertyDefinition, U extends PropertyDefinition> void validateGetFunction(final T property,
2390 final List<U> parentProperties,
2391 final String model) {
2392 final ToscaGetFunctionDataDefinition toscaGetFunction = property.getToscaGetFunction();
2393 if (CollectionUtils.isEmpty(parentProperties)) {
2394 throw ToscaGetFunctionExceptionSupplier
2395 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource(),
2396 toscaGetFunction.getFunctionType()
2399 validateGetPropertySource(toscaGetFunction.getFunctionType(), toscaGetFunction.getPropertySource());
2400 final String getFunctionPropertyUniqueId = toscaGetFunction.getPropertyUniqueId();
2401 T referredProperty = (T) parentProperties.stream()
2402 .filter(property1 -> getFunctionPropertyUniqueId.equals(property1.getUniqueId()))
2404 .orElseThrow(ToscaGetFunctionExceptionSupplier
2405 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource()
2406 , toscaGetFunction.getFunctionType())
2408 if (toscaGetFunction.isSubProperty()) {
2409 referredProperty = findSubProperty(referredProperty, toscaGetFunction, model);
2412 if (!property.getType().equals(referredProperty.getType())) {
2413 throw ToscaGetFunctionExceptionSupplier
2414 .propertyTypeDiverge(toscaGetFunction.getFunctionType(), referredProperty.getType(), property.getType()).get();
2416 if (PropertyType.typeHasSchema(referredProperty.getType()) && !referredProperty.getSchemaType().equals(property.getSchemaType())) {
2417 throw ToscaGetFunctionExceptionSupplier
2418 .propertySchemaDiverge(toscaGetFunction.getFunctionType(), referredProperty.getSchemaType(), property.getSchemaType()).get();
2422 private <T extends PropertyDefinition> T findSubProperty(final T referredProperty, final ToscaGetFunctionDataDefinition toscaGetFunction,
2423 final String model) {
2424 final Map<String, DataTypeDefinition> dataTypeMap = loadDataTypes(model);
2425 final List<String> propertyPathFromSource = toscaGetFunction.getPropertyPathFromSource();
2426 DataTypeDefinition dataType = dataTypeMap.get(referredProperty.getType());
2427 if (dataType == null) {
2428 throw ToscaGetFunctionExceptionSupplier
2429 .propertyDataTypeNotFound(propertyPathFromSource.get(0), referredProperty.getType(), toscaGetFunction.getFunctionType()).get();
2431 T foundProperty = referredProperty;
2432 for (int i = 1; i < propertyPathFromSource.size(); i++) {
2433 final String currentPropertyName = propertyPathFromSource.get(i);
2434 foundProperty = (T) dataType.getProperties().stream()
2435 .filter(propertyDefinition -> currentPropertyName.equals(propertyDefinition.getName())).findFirst()
2437 ToscaGetFunctionExceptionSupplier
2438 .propertyNotFoundOnTarget(propertyPathFromSource.subList(0, i), toscaGetFunction.getPropertySource(),
2439 toscaGetFunction.getFunctionType())
2441 dataType = dataTypeMap.get(foundProperty.getType());
2442 if (dataType == null) {
2443 throw ToscaGetFunctionExceptionSupplier
2444 .propertyDataTypeNotFound(propertyPathFromSource.subList(0, i), foundProperty.getType(),
2445 toscaGetFunction.getFunctionType()).get();
2448 return foundProperty;
2451 private Map<String, DataTypeDefinition> loadDataTypes(String model) {
2452 final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeEither =
2453 applicationDataTypeCache.getAll(model);
2454 if (dataTypeEither.isRight()) {
2455 throw ToscaGetFunctionExceptionSupplier.couldNotLoadDataTypes(model).get();
2457 return dataTypeEither.left().value();
2460 private void validateGetPropertySource(final ToscaGetFunctionType functionType, final PropertySource propertySource) {
2461 if (propertySource != PropertySource.SELF) {
2462 throw ToscaGetFunctionExceptionSupplier
2463 .targetSourceNotSupported(functionType, propertySource).get();
2467 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
2468 ComponentInstance foundResourceInstance) {
2469 StorageOperationStatus status;
2470 input.setValue(newValue);
2471 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
2472 if (status != StorageOperationStatus.OK) {
2473 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2474 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2476 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2477 return componentsUtils.getResponseFormat(ActionStatus.OK);
2480 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
2481 String componentId, String resourceInstanceId,
2482 List<ComponentInstanceInput> inputs,
2485 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
2487 validateUserExists(userId);
2489 if (componentTypeEnum == null) {
2490 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2491 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2494 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2496 if (getResourceResult.isRight()) {
2497 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2498 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2499 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2501 Component containerComponent = getResourceResult.left().value();
2503 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2504 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2505 log.info(COMPONENT_ARCHIVED, componentId);
2506 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2508 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2509 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2512 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2513 if (resourceInstanceStatus.isRight()) {
2514 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2515 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2518 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2521 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2522 if (lockStatus != StorageOperationStatus.OK) {
2523 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2524 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2526 List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
2528 for (ComponentInstanceInput input : inputs) {
2529 validateMandatoryFields(input);
2530 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
2531 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
2532 if (validatedInputValue.isRight()) {
2533 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2535 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
2536 foundResourceInstance);
2537 updatedInputs.add(componentInstanceInput);
2539 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2540 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2541 if (updateContainerRes.isRight()) {
2542 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2543 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2546 resultOp = Either.left(updatedInputs);
2550 if (resultOp == null || resultOp.isRight()) {
2551 janusGraphDao.rollback();
2553 janusGraphDao.commit();
2556 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2561 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
2562 ComponentInstance foundResourceInstance) {
2563 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2564 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2565 if (!instanceInput.isPresent()) {
2566 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2568 return instanceInput.get();
2571 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
2572 String componentId, String resourceInstanceId,
2573 String groupInstanceId,
2574 ComponentInstanceProperty property,
2577 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2579 validateUserExists(userId);
2581 if (componentTypeEnum == null) {
2582 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2583 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2587 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2588 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2589 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2593 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2594 if (lockStatus != StorageOperationStatus.OK) {
2595 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2596 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2600 String propertyValueUid = property.getValueUniqueUid();
2602 if (propertyValueUid == null) {
2604 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
2605 .increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2607 if (counterRes.isRight()) {
2608 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2609 StorageOperationStatus status = counterRes.right().value();
2610 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2611 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2613 Integer index = counterRes.left().value();
2614 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2615 .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2617 if (result.isLeft()) {
2618 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2619 ComponentInstanceProperty instanceProperty = result.left().value();
2621 resultOp = Either.left(instanceProperty);
2624 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2626 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2628 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2632 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2633 .updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2635 if (result.isLeft()) {
2636 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2637 ComponentInstanceProperty instanceProperty = result.left().value();
2639 resultOp = Either.left(instanceProperty);
2642 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2644 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2646 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2649 if (resultOp.isLeft()) {
2650 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2651 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2652 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2654 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2661 if (resultOp == null || resultOp.isRight()) {
2662 janusGraphDao.rollback();
2664 janusGraphDao.commit();
2667 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2672 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
2673 String resourceInstanceId, String propertyValueId, String userId) {
2675 validateUserExists(userId);
2677 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2679 if (componentTypeEnum == null) {
2680 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2681 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2685 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2686 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2687 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2691 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2692 if (lockStatus != StorageOperationStatus.OK) {
2693 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2694 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2698 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
2699 .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2701 if (result.isLeft()) {
2702 log.debug("Property value {} was removed from graph.", propertyValueId);
2703 ComponentInstanceProperty instanceProperty = result.left().value();
2705 resultOp = Either.left(instanceProperty);
2709 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2711 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2713 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2719 if (resultOp == null || resultOp.isRight()) {
2720 janusGraphDao.rollback();
2722 janusGraphDao.commit();
2725 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2730 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2732 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2733 Component component;
2734 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2735 if (getComponentRes.isRight()) {
2736 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
2737 componentInstance.getName());
2738 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2739 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2741 component = getComponentRes.left().value();
2742 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2743 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2744 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2745 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2747 if (Boolean.TRUE.equals(component.isArchived())) {
2748 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2749 throw new ByActionStatusComponentException(actionStatus, component.getName());
2751 final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2752 if (MapUtils.isNotEmpty(componentInterfaces)) {
2753 componentInterfaces.forEach(componentInstance::addInterface);
2758 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2759 String containerComponentId,
2760 String componentInstanceId,
2761 ComponentInstance newComponentInstance) {
2762 Either<Set<String>, ResponseFormat> resultOp;
2763 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2764 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2767 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2769 //Fetch current component instance
2770 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2771 getResourceInstanceById(containerComponent, componentInstanceId);
2772 if (eitherResourceInstance.isRight()) {
2773 resultOp = Either.right(componentsUtils.getResponseFormat(
2774 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2777 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2779 //Check whether new componentInstance exists
2780 String resourceId = newComponentInstance.getComponentUid();
2781 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2782 if (componentExistsRes.isRight()) {
2783 log.debug("Failed to find resource {}", resourceId);
2784 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2785 (componentExistsRes.right().value()), resourceId));
2787 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2788 log.debug("The resource {} not found ", resourceId);
2789 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2793 //Fetch component using new component instance uid
2794 Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2795 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2796 currentResourceInstance, updatedContainerComponent);
2797 resultOp = Either.left(toDeleteForwardingPaths);
2802 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2803 Component updatedContainerComponent) {
2804 DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
2805 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2807 Service service = (Service) containerComponent;
2808 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2810 return forwardingPathUtils.
2811 getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
2814 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2815 ComponentParametersView componentParametersView = new ComponentParametersView();
2816 componentParametersView.setIgnoreCapabiltyProperties(false);
2817 componentParametersView.setIgnoreServicePath(false);
2818 return componentParametersView;
2821 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
2822 String userId, ComponentInstance newComponentInstance) {
2824 User user = validateUserExists(userId);
2825 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2826 ComponentParametersView componentParametersView = new ComponentParametersView();
2827 componentParametersView.setIgnoreCapabiltyProperties(false);
2829 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
2830 componentParametersView);
2832 validateCanWorkOnComponent(containerComponent, userId);
2834 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2835 if (resourceInstanceStatus.isRight()) {
2836 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
2837 containerComponentId);
2840 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2842 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
2845 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
2846 ComponentInstance currentResourceInstance,
2847 ComponentInstance newComponentInstance,
2849 final ComponentTypeEnum containerComponentType) {
2850 boolean failed = false;
2851 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2854 lockComponent(containerComponent, "changeComponentInstanceVersion");
2855 String containerComponentId = containerComponent.getUniqueId();
2856 String componentInstanceId = currentResourceInstance.getUniqueId();
2857 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2858 return currentResourceInstance;
2860 String resourceId = newComponentInstance.getComponentUid();
2862 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
2863 .validateComponentExists(resourceId);
2864 if (componentExistsRes.isRight()) {
2865 StorageOperationStatus errorStatus = componentExistsRes.right().value();
2867 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
2868 throw new ByActionStatusComponentException(
2869 componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
2870 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2871 log.debug("The resource {} not found ", resourceId);
2872 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2875 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2876 DataForMergeHolder dataHolder = compInstMergeDataBL
2877 .saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2878 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
2879 containerComponentType);
2881 if (resResourceInfo == null) {
2882 log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
2883 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2885 Component origComponent = null;
2886 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2887 newComponentInstance.setOriginType(originType);
2888 if (originType == OriginTypeEnum.ServiceProxy) {
2889 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
2890 .getLatestByName(SERVICE_PROXY, null);
2891 if (isServiceProxyOrigin(serviceProxyOrigin)) {
2892 throw new ByActionStatusComponentException(
2893 componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2895 origComponent = serviceProxyOrigin.left().value();
2897 StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2899 if (isFillProxyRes(fillProxyRes)) {
2900 throw new ByActionStatusComponentException(
2901 componentsUtils.convertFromStorageResponse(fillProxyRes));
2903 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
2904 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
2905 .getToscaFullElement(newComponentInstance.getComponentUid());
2906 if (getServiceResult.isRight()) {
2907 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2909 final Component service = getServiceResult.left().value();
2911 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
2912 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
2913 if (getServiceDerivedFromTypeResult.isRight()) {
2914 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2917 origComponent = getServiceDerivedFromTypeResult.left().value();
2919 final StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2920 if (isFillProxyRes(fillProxyRes)) {
2921 throw new ByActionStatusComponentException(
2922 componentsUtils.convertFromStorageResponse(fillProxyRes));
2925 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2926 newComponentInstance.setName(resResourceInfo.getName());
2927 final Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade
2928 .getToscaFullElement(newComponentInstance.getComponentUid());
2929 if (getComponentRes.isRight()) {
2930 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
2932 final Component component = getComponentRes.left().value();
2933 final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2934 if (MapUtils.isNotEmpty(componentInterfaces)) {
2935 componentInterfaces.forEach(newComponentInstance::addInterface);
2939 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2940 newComponentInstance.setPosX(resResourceInfo.getPosX());
2941 newComponentInstance.setPosY(resResourceInfo.getPosY());
2942 newComponentInstance.setDescription(resResourceInfo.getDescription());
2943 newComponentInstance.setInstanceCount(resResourceInfo.getInstanceCount());
2944 newComponentInstance.setMaxOccurrences(resResourceInfo.getMaxOccurrences());
2945 newComponentInstance.setMinOccurrences(resResourceInfo.getMinOccurrences());
2947 ComponentInstance updatedComponentInstance =
2948 createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2949 dataHolder.setCurrInstanceNode(origComponent);
2951 .mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2953 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
2954 .doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2955 if (postChangeVersionResult != ActionStatus.OK) {
2956 throw new ByActionStatusComponentException(postChangeVersionResult);
2959 ComponentParametersView filter = new ComponentParametersView(true);
2960 filter.setIgnoreComponentInstances(false);
2961 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2962 if (updatedComponentRes.isRight()) {
2963 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2964 ActionStatus actionStatus = componentsUtils
2965 .convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2966 log.debug("Component with id {} was not found", containerComponentId);
2967 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2969 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
2970 updatedComponentInstance.getUniqueId());
2971 if (resourceInstanceStatus.isRight()) {
2972 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
2973 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
2975 return resourceInstanceStatus.left().value();
2977 } catch (ComponentException e) {
2981 unlockComponent(failed, containerComponent);
2985 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
2986 if (fillProxyRes != StorageOperationStatus.OK) {
2987 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2994 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
2995 String componentInstanceUniqueId, String userId) {
2996 Component containerComponent = null;
2998 boolean failed = false;
3000 validateUserExists(userId);
3001 validateComponentType(containerComponentTypeParam);
3003 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
3004 if (validateContainerComponentExists.isRight()) {
3005 throw new ByActionStatusComponentException(
3006 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3008 containerComponent = validateContainerComponentExists.left().value();
3010 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3011 componentInstanceUniqueId);
3012 if (resourceInstanceStatus.isRight()) {
3013 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
3014 containerComponentId);
3017 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
3018 if (CollectionUtils.isEmpty(instanceProperties)) {
3019 instanceProperties = new ArrayList<>();
3021 return instanceProperties;
3022 } catch (ComponentException e) {
3026 unlockComponent(failed, containerComponent);
3030 public List<ComponentInstanceAttribute> getComponentInstanceAttributesById(final String containerComponentTypeParam,
3031 final String containerComponentId,
3032 final String componentInstanceUniqueId,
3033 final String userId) {
3034 Component containerComponent = null;
3036 boolean failed = false;
3038 validateUserExists(userId);
3039 validateComponentType(containerComponentTypeParam);
3041 final Either<Component, StorageOperationStatus> validateContainerComponentExists =
3042 toscaOperationFacade.getToscaElement(containerComponentId);
3043 if (validateContainerComponentExists.isRight()) {
3044 throw new ByActionStatusComponentException(
3045 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3047 containerComponent = validateContainerComponentExists.left().value();
3049 if (getResourceInstanceById(containerComponent, componentInstanceUniqueId).isRight()) {
3050 throw new ByActionStatusComponentException(
3051 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
3054 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = containerComponent.getComponentInstancesAttributes();
3055 return componentInstancesAttributes == null ? new ArrayList<>()
3056 : componentInstancesAttributes.getOrDefault(componentInstanceUniqueId, new ArrayList<>());
3057 } catch (final ComponentException e) {
3061 unlockComponent(failed, containerComponent);
3065 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType,
3066 Wrapper<Integer> instaceCounterWrapper,
3067 Wrapper<ResponseFormat> errorWrapper) {
3068 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation
3069 .increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
3071 if (counterRes.isRight()) {
3072 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
3073 StorageOperationStatus status = counterRes.right().value();
3074 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3075 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
3077 instaceCounterWrapper.setInnerElement(counterRes.left().value());
3083 * updates componentInstance modificationTime
3085 * @param componentInstance
3086 * @param componentInstanceType
3087 * @param modificationTime
3088 * @param inTransaction
3091 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
3092 ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
3093 Either<ComponentInstanceData, ResponseFormat> result;
3094 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
3095 .updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
3097 if (updateComponentInstanceRes.isRight()) {
3098 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
3099 updateComponentInstanceRes.right().value());
3101 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
3103 result = Either.left(updateComponentInstanceRes.left().value());
3108 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
3109 // TODO Add implementation
3110 return Either.left(new ComponentInstance());
3113 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
3114 // TODO Add implementation
3115 return Either.left(new ComponentInstance());
3118 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
3119 // TODO Add implementation
3120 return Either.left(new ComponentInstance());
3123 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
3124 String newInstanceName) {
3125 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
3128 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(final Component containerComponent, final String instanceId) {
3129 final List<ComponentInstance> instances = containerComponent.getComponentInstances();
3130 if (CollectionUtils.isEmpty(instances)) {
3131 return Either.right(StorageOperationStatus.NOT_FOUND);
3134 final Optional<ComponentInstance> foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
3135 if (foundInstance.isEmpty()) {
3136 return Either.right(StorageOperationStatus.NOT_FOUND);
3139 return Either.left(foundInstance.get());
3142 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
3143 Long creationDate = origInstanceForUpdate.getCreationTime();
3144 Long modificationTime = System.currentTimeMillis();
3145 resourceInstanceForUpdate.setCreationTime(creationDate);
3146 resourceInstanceForUpdate.setModificationTime(modificationTime);
3147 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
3148 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
3149 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
3151 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
3152 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
3153 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
3155 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
3156 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
3158 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
3159 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
3161 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
3162 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
3164 if (resourceInstanceForUpdate.getOriginType() == null) {
3165 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
3167 if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
3168 resourceInstanceForUpdate.setIsProxy(true);
3170 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
3171 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
3173 if (resourceInstanceForUpdate.getSourceModelName() == null) {
3174 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
3176 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
3177 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
3179 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
3180 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
3182 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
3183 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
3185 return resourceInstanceForUpdate;
3189 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3191 * @param containerComponentType
3192 * @param containerComponentId
3193 * @param componentInstanceUniqueId
3194 * @param capabilityType
3195 * @param capabilityName
3200 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
3201 String componentInstanceUniqueId, String capabilityType,
3202 String capabilityName, String ownerId, String userId) {
3203 Component containerComponent = null;
3204 List<ComponentInstanceProperty> resultOp = null;
3206 validateUserExists(userId);
3207 validateComponentType(containerComponentType);
3208 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
3209 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left()
3210 .on(this::componentInstanceException);
3211 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId,
3212 resourceInstanceStatus.getCapabilities());
3213 } catch (StorageException | ComponentException e) {
3214 unlockRollbackWithException(containerComponent, e);
3215 } catch (Exception e) {
3216 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
3218 unlockWithCommit(containerComponent);
3222 private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
3223 String capabilityName, String ownerId,
3224 Map<String, List<CapabilityDefinition>> instanceCapabilities) {
3225 CapabilityDefinition foundCapability;
3226 if (MapUtils.isNotEmpty(instanceCapabilities)) {
3227 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
3228 if (capabilitiesPerType != null) {
3229 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
3230 .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
3231 if (capabilityOpt.isPresent()) {
3232 foundCapability = capabilityOpt.get();
3233 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
3237 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
3240 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
3241 String capabilityName, String ownerId) {
3243 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
3244 .left().on(this::componentInstancePropertyListException);
3245 } catch (Exception e) {
3246 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
3248 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
3252 public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
3253 String componentInstanceUniqueId,
3254 RequirementDefinition requirementDef, String userId) {
3255 Either<RequirementDefinition, ResponseFormat> resultOp = null;
3256 validateUserExists(userId);
3257 if (componentTypeEnum == null) {
3258 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3259 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3261 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3262 if (getResourceResult.isRight()) {
3263 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3264 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3266 Component containerComponent = getResourceResult.left().value();
3267 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3268 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3269 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3271 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3272 componentInstanceUniqueId);
3273 if (resourceInstanceStatus.isRight()) {
3274 return Either.right(componentsUtils
3275 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3278 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3279 if (lockStatus != StorageOperationStatus.OK) {
3280 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3281 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3284 StorageOperationStatus updateRequirementStatus = toscaOperationFacade
3285 .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
3286 if (updateRequirementStatus != StorageOperationStatus.OK) {
3287 log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
3288 containerComponentId);
3289 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
3291 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3292 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3293 if (updateContainerRes.isRight()) {
3294 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3295 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3298 resultOp = Either.left(requirementDef);
3301 if (resultOp == null || resultOp.isRight()) {
3302 janusGraphDao.rollback();
3304 janusGraphDao.commit();
3307 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3311 public Either<CapabilityDefinition, ResponseFormat> updateInstanceCapability(final ComponentTypeEnum containerComponentType,
3312 final String containerComponentId,
3313 final String componentInstanceUniqueId,
3314 final CapabilityDefinition capabilityDefinition,
3315 final String userId) {
3316 if (containerComponentType == null) {
3317 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapability", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3318 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3320 validateUserExists(userId);
3321 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3322 if (getResourceResult.isRight()) {
3323 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3324 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, containerComponentId));
3326 final Component containerComponent = getResourceResult.left().value();
3327 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3328 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3329 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3331 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus =
3332 getResourceInstanceById(containerComponent, componentInstanceUniqueId);
3333 if (resourceInstanceStatus.isRight()) {
3334 return Either.right(componentsUtils
3335 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3338 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, containerComponentType.getNodeType());
3339 if (lockStatus != StorageOperationStatus.OK) {
3340 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3341 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3343 var success = false;
3345 final CapabilityDataDefinition updatedCapabilityDefinition = toscaOperationFacade
3346 .updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition);
3347 final Either<Component, StorageOperationStatus> updateContainerEither = toscaOperationFacade
3348 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3349 if (updateContainerEither.isRight()) {
3350 var actionStatus = componentsUtils.convertFromStorageResponse(updateContainerEither.right().value(), containerComponentType);
3351 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3354 return Either.left(new CapabilityDefinition(updatedCapabilityDefinition));
3355 } catch (final BusinessException e) {
3356 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3357 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3359 } catch (final Exception e) {
3360 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3361 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3362 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3365 janusGraphDao.commit();
3367 janusGraphDao.rollback();
3370 graphLockOperation.unlockComponent(containerComponentId, containerComponentType.getNodeType());
3374 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
3375 String containerComponentId,
3376 String componentInstanceUniqueId,
3377 String capabilityType, String capabilityName,
3378 List<ComponentInstanceProperty> properties,
3380 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
3381 validateUserExists(userId);
3382 if (componentTypeEnum == null) {
3383 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3384 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3386 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3387 if (getResourceResult.isRight()) {
3388 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3389 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3391 Component containerComponent = getResourceResult.left().value();
3392 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3393 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3394 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3396 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3397 componentInstanceUniqueId);
3398 if (resourceInstanceStatus.isRight()) {
3399 return Either.right(componentsUtils
3400 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3402 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3404 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3405 if (lockStatus != StorageOperationStatus.OK) {
3406 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3407 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3410 for (ComponentInstanceProperty property : properties) {
3411 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
3412 newPropertyValueEither.bimap(
3413 updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
3414 capabilityType, capabilityName), Either::right);
3416 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3417 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3418 if (updateContainerRes.isRight()) {
3419 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3420 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3423 resultOp = Either.left(properties);
3426 if (resultOp == null || resultOp.isRight()) {
3427 janusGraphDao.rollback();
3429 janusGraphDao.commit();
3432 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3436 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
3437 String containerComponentId, String componentInstanceId,
3439 Map<String, ComponentInstance> resultMap = new HashMap<>();
3440 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3441 if (getOrigComponent.isRight()) {
3442 log.error("Failed to get the original component information");
3443 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3445 Component origComponent = getOrigComponent.left().value();
3447 lockComponent(origComponent, "copyComponentInstance");
3448 } catch (ComponentException e) {
3449 log.error("destComponentInstance's data is {}", origComponent.toString());
3450 return Either.right(componentsUtils
3451 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
3452 origComponent.toString()));
3454 boolean failed = false;
3455 ComponentInstance actionResponse = null;
3457 actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
3458 } catch (ComponentException e) {
3460 // on failure of the create instance unlock the resource and rollback the transaction.
3461 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3463 // on failure of the create instance unlock the resource and rollback the transaction.
3464 if (null == actionResponse) {
3465 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
3466 unlockComponent(failed, origComponent);
3469 Either<String, ResponseFormat> resultOp = null;
3471 ComponentInstance destComponentInstance = actionResponse;
3472 log.debug("destComponentInstance's data is {}", destComponentInstance);
3473 resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
3474 resultMap.put("componentInstance", destComponentInstance);
3477 if (resultOp == null || resultOp.isRight()) {
3478 unlockComponent(true, origComponent);
3479 janusGraphDao.rollback();
3480 log.error("Failed to deep copy component instance");
3482 unlockComponent(false, origComponent);
3483 janusGraphDao.commit();
3484 log.debug("Success trasaction commit");
3487 if (resultOp == null || resultOp.isRight()) {
3489 .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
3491 return Either.left(resultMap);
3495 private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
3496 String sourceComponentInstanceId, ComponentInstance destComponentInstance,
3498 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3499 if (getDestComponent.isRight()) {
3500 log.error("Failed to get the dest component information");
3501 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3503 Component destComponent = getDestComponent.left().value();
3504 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
3505 destComponent, sourceComponentInstanceId, destComponentInstance);
3506 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
3507 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
3508 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
3509 "Failed to copy the component instance with properties and inputs as part of deep copy"));
3511 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
3512 sourceComponentInstanceId, destComponentInstance, userId);
3513 if (copyComponentInstanceWithAttributes.isRight()) {
3514 log.error("Failed to copy component instance with attributes as part of deep copy");
3515 return Either.right(componentsUtils
3516 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
3518 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3521 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
3522 String sourceComponentInstanceId,
3523 ComponentInstance destComponentInstance) {
3524 log.debug("start to copy ComponentInstance with properties and inputs");
3525 List<ComponentInstanceProperty> sourcePropList = null;
3526 if (sourceComponent.getComponentInstancesProperties() != null
3527 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
3528 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
3529 log.debug("sourcePropList");
3531 List<ComponentInstanceProperty> destPropList = null;
3532 String destComponentInstanceId = destComponentInstance.getUniqueId();
3533 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
3534 if (destComponent.getComponentInstancesProperties() != null
3535 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
3536 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
3537 log.debug("destPropList {}");
3539 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
3540 if (null != destPropList && null != sourcePropList) {
3541 log.debug("start to set property and attribute");
3542 for (ComponentInstanceProperty destProp : destPropList) {
3543 String destPropertyName = destProp.getName();
3544 for (ComponentInstanceProperty sourceProp : sourcePropList) {
3545 if (!destPropertyName.equals(sourceProp.getName())) {
3548 log.debug("now set property");
3549 final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
3550 if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
3551 .equals(sourceProp.getValue()))) {
3552 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
3553 destProp.setValue(sourceProp.getValue());
3554 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
3555 destComponentInstanceId, destProp);
3556 if (updatePropertyValueEither.isRight()) {
3557 log.error("Failed to copy the property {}", destPropertyName);
3558 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3559 "Failed to paste component instance to the canvas, property copy"));
3563 log.debug("Now start to update inputs");
3564 if (getInputValues != null) {
3565 if (getInputValues.isEmpty()) {
3566 log.debug("property is return from input, set by man");
3569 log.debug("Now starting to copy the {} property", destPropertyName);
3570 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
3571 getInputValues.get(0).getInputId());
3572 if (getSourceInputDefaultValue.isRight()) {
3573 return Either.right(getSourceInputDefaultValue.right().value());
3575 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
3580 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3583 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
3584 String sourceComponentInstanceId,
3585 ComponentInstance destComponentInstance, String userId) {
3586 String destComponentInstanceId = destComponentInstance.getUniqueId();
3587 log.info("start to copy component instance with attributes");
3588 List<ComponentInstanceAttribute> sourceAttributeList = null;
3589 if (sourceComponent.getComponentInstancesAttributes() != null
3590 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
3591 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
3592 log.info("sourceAttributes {}");
3594 List<ComponentInstanceAttribute> destAttributeList = null;
3595 if (destComponent.getComponentInstancesAttributes() != null
3596 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
3597 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
3598 log.info("destAttributeList {}");
3600 if (null != sourceAttributeList && null != destAttributeList) {
3601 log.info("set attribute");
3602 for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
3603 String sourceAttributeName = sourceAttribute.getName();
3604 for (ComponentInstanceAttribute destAttribute : destAttributeList) {
3605 if (sourceAttributeName.equals(destAttribute.getName())) {
3606 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
3607 sourceAttribute.setUniqueId(
3608 UniqueIdBuilder.buildResourceInstanceUniuqeId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
3609 Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
3610 ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
3611 if (updateAttributeValueEither.isRight()) {
3612 log.error("Failed to copy the attribute");
3613 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3614 "Failed to paste component instance to the canvas, attribute copy"));
3621 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3624 private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
3625 String componentId, String resourceInstanceId,
3626 ComponentInstanceAttribute attribute,
3628 Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
3629 validateUserExists(userId);
3630 if (componentTypeEnum == null) {
3631 BeEcompErrorManager.getInstance()
3632 .logInvalidInputError("createOrUpdateAttributeValueForCopyPaste", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3633 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3636 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3637 if (getResourceResult.isRight()) {
3638 log.info("Failed to retrieve component id {}", componentId);
3639 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3642 Component containerComponent = getResourceResult.left().value();
3643 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3644 if (resourceInstanceStatus.isRight()) {
3646 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3649 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3650 String propertyType = attribute.getType();
3651 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3652 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3653 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3654 SchemaDefinition def = attribute.getSchema();
3656 log.info("Schema doesn't exists for attribute of type {}", type);
3658 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3660 PropertyDataDefinition propDef = def.getProperty();
3661 if (propDef == null) {
3662 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3664 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3667 List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
3668 Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
3669 .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3670 StorageOperationStatus status;
3671 if (instanceAttribute.isPresent()) {
3672 log.info("updateComponentInstanceAttribute");
3673 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3675 log.info("addComponentInstanceAttribute");
3676 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3678 if (status != StorageOperationStatus.OK) {
3679 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3680 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3683 List<String> path = new ArrayList<>();
3684 path.add(foundResourceInstance.getUniqueId());
3685 attribute.setPath(path);
3686 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3687 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3688 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3689 if (updateContainerRes.isRight()) {
3690 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3691 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3694 resultOp = Either.left(attribute);
3698 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
3699 ComponentInstanceProperty property) {
3700 Either<String, ResponseFormat> resultOp;
3701 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3702 if (getComponent.isRight()) {
3703 log.error("Failed to get the component information");
3704 return Either.right(componentsUtils
3705 .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3707 Component containerComponent = getComponent.left().value();
3708 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3709 if (status != StorageOperationStatus.OK) {
3710 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3711 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3714 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3715 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3716 if (updateContainerRes.isRight()) {
3717 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3718 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3721 return Either.left("Update OK");
3724 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3725 List<InputDefinition> inputList = component.getInputs();
3726 for (InputDefinition input : inputList) {
3727 if (input.getUniqueId().equals(inputId)) {
3728 if (input.getDefaultValue() == null) {
3729 log.debug("The input's default value is null");
3730 return Either.left(null);
3732 return Either.left(input.getDefaultValue());
3735 log.error("The input's default value with id {} is not found", inputId);
3736 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3740 * Method to delete selected nodes and edges on composition page
3742 * @param containerComponentType
3743 * @param componentId
3744 * @param componentInstanceIdList
3748 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
3749 List<String> componentInstanceIdList, String userId) {
3750 List<String> deleteErrorIds = new ArrayList<>();
3751 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3752 validateUserExists(userId);
3753 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
3754 ComponentTypeEnum.findByParamName(containerComponentType), null);
3755 boolean failed = false;
3757 lockComponent(containerComponent, "batchDeleteComponentInstance");
3758 for (String eachInstanceId : componentInstanceIdList) {
3759 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
3761 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3762 if (actionResponse.isRight()) {
3763 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3764 deleteErrorIds.add(eachInstanceId);
3767 //sending the ids of the error nodes that were not deleted to UI
3768 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3769 return deleteErrorMap;
3770 } catch (ComponentException e) {
3774 unlockComponent(failed, containerComponent);
3778 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
3779 String componentInstanceId) {
3780 ComponentInstance resultOp;
3781 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3783 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3784 log.info("Successfully deleted instance with id {}", componentInstanceId);
3785 return Either.left(resultOp);
3786 } catch (ComponentException e) {
3787 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3788 return Either.right(new ResponseFormat());
3792 public void validateUser(final String userId) {
3793 final User user = userValidations.validateUserExists(userId);
3794 userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
3797 public void setCompositionBusinessLogic(CompositionBusinessLogic compositionBusinessLogic) {
3798 this.compositionBusinessLogic = compositionBusinessLogic;
3801 public void setContainerInstanceTypesData(ContainerInstanceTypesData containerInstanceTypesData) {
3802 this.containerInstanceTypesData = containerInstanceTypesData;