2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import 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.function.BiConsumer;
42 import java.util.stream.Collectors;
43 import org.apache.commons.collections.CollectionUtils;
44 import org.apache.commons.collections.MapUtils;
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.commons.lang3.tuple.ImmutablePair;
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.instance.ComponentInstanceChangeOperationOrchestrator;
52 import org.openecomp.sdc.be.components.impl.utils.DirectivesEnum;
53 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
54 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
55 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
56 import org.openecomp.sdc.be.components.validation.ComponentValidations;
57 import org.openecomp.sdc.be.config.BeEcompErrorManager;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
59 import org.openecomp.sdc.be.config.ConfigurationManager;
60 import org.openecomp.sdc.be.dao.api.ActionStatus;
61 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
62 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
63 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
64 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
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.GetPolicyValueDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
73 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
74 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
75 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
76 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
77 import org.openecomp.sdc.be.impl.ComponentsUtils;
78 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
79 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
80 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
81 import org.openecomp.sdc.be.model.ArtifactDefinition;
82 import org.openecomp.sdc.be.model.CapabilityDefinition;
83 import org.openecomp.sdc.be.model.Component;
84 import org.openecomp.sdc.be.model.ComponentInstance;
85 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
86 import org.openecomp.sdc.be.model.ComponentInstanceInput;
87 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
88 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
89 import org.openecomp.sdc.be.model.ComponentParametersView;
90 import org.openecomp.sdc.be.model.DataTypeDefinition;
91 import org.openecomp.sdc.be.model.GroupDefinition;
92 import org.openecomp.sdc.be.model.InputDefinition;
93 import org.openecomp.sdc.be.model.InterfaceDefinition;
94 import org.openecomp.sdc.be.model.LifecycleStateEnum;
95 import org.openecomp.sdc.be.model.PolicyDefinition;
96 import org.openecomp.sdc.be.model.PropertyDefinition;
97 import org.openecomp.sdc.be.model.RelationshipInfo;
98 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
99 import org.openecomp.sdc.be.model.RequirementDefinition;
100 import org.openecomp.sdc.be.model.Resource;
101 import org.openecomp.sdc.be.model.Service;
102 import org.openecomp.sdc.be.model.User;
103 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
104 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
105 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
106 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
107 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
108 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
109 import org.openecomp.sdc.be.model.operations.StorageException;
110 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
111 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
112 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
113 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
114 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
115 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
116 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
117 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
118 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
119 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
120 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
121 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
122 import org.openecomp.sdc.be.user.Role;
123 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
124 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
125 import org.openecomp.sdc.common.api.Constants;
126 import org.openecomp.sdc.common.datastructure.Wrapper;
127 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
128 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
129 import org.openecomp.sdc.common.log.wrappers.Logger;
130 import org.openecomp.sdc.common.util.ValidationUtils;
131 import org.openecomp.sdc.exception.ResponseFormat;
132 import org.springframework.beans.factory.annotation.Autowired;
134 @org.springframework.stereotype.Component
135 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
137 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class);
138 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
139 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
140 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
141 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
142 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
143 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
144 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
145 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
146 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
147 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
148 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
149 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
150 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
152 private ComponentInstanceOperation componentInstanceOperation;
153 private ArtifactsBusinessLogic artifactBusinessLogic;
154 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
155 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
156 private ForwardingPathOperation forwardingPathOperation;
157 private NodeFilterOperation nodeFilterOperation;
160 public ComponentInstanceBusinessLogic(IElementOperation elementDao,
161 IGroupOperation groupOperation,
162 IGroupInstanceOperation groupInstanceOperation,
163 IGroupTypeOperation groupTypeOperation,
164 InterfaceOperation interfaceOperation,
165 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
166 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
167 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
168 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
169 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
170 ArtifactsOperations artifactToscaOperation) {
171 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
172 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
173 this.componentInstanceOperation = componentInstanceOperation;
174 this.artifactBusinessLogic = artifactBusinessLogic;
175 this.compInstMergeDataBL = compInstMergeDataBL;
176 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
177 this.forwardingPathOperation = forwardingPathOperation;
178 this.nodeFilterOperation = nodeFilterOperation;
182 private CompositionBusinessLogic compositionBusinessLogic;
185 private ContainerInstanceTypesData containerInstanceTypesData;
187 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
188 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
191 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
192 List<ComponentInstanceProperty> resList = new ArrayList<>();
193 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
194 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
195 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
197 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
199 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
201 ciName = ciOp.get().getName();
202 if (ciPropList != null && !ciPropList.isEmpty()) {
203 for(ComponentInstanceProperty prop: ciPropList){
204 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
205 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
215 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceProperty> resList) {
216 if(inputsValues != null && !inputsValues.isEmpty()){
217 for(GetInputValueDataDefinition inputData: inputsValues){
218 if(isGetInputValueForInput(inputData, inputId)){
219 prop.setComponentInstanceId(s);
220 prop.setComponentInstanceName(ciName);
228 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component,
229 PolicyDefinition policy) {
231 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
233 if(propertyCandidate.isPresent()) {
234 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
235 Optional<GetPolicyValueDataDefinition> getPolicyCandidate =
236 getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
238 getPolicyCandidate.ifPresent(getPolicyValue ->
239 updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
240 return Optional.of(componentInstanceProperty);
243 return Optional.empty();
247 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
248 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
249 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
250 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
251 if(CollectionUtils.isNotEmpty(getPolicyValues)) {
252 getPolicyValues.remove(getPolicyValue);
253 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
254 policyDefinition.setGetPolicyValues(getPolicyValues);
258 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
259 ComponentInstanceProperty componentInstanceProperty) {
260 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
261 return getPolicyValues.stream()
262 .filter(getPolicyValue -> getPolicyValue
264 .equals(componentInstanceProperty
269 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component,
270 PolicyDefinition policy) {
271 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
272 component.getComponentInstancesProperties();
274 if(MapUtils.isEmpty(componentInstancesProperties)) {
275 return Optional.empty();
278 String instanceUniqueId = policy.getInstanceUniqueId();
280 List<ComponentInstanceProperty> componentInstanceProperties =
281 componentInstancesProperties.containsKey(instanceUniqueId)
282 ? componentInstancesProperties.get(instanceUniqueId)
285 return componentInstanceProperties
286 .stream().filter(property -> property.getName().equals(policy.getName())).findAny();
289 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(
290 org.openecomp.sdc.be.model.Component component, String inputId) {
291 List<ComponentInstanceInput> resList = new ArrayList<>();
292 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
293 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
294 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
296 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
298 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
300 ciName = ciOp.get().getName();
301 if (ciPropList != null && !ciPropList.isEmpty()) {
302 for(ComponentInstanceInput prop: ciPropList){
303 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
304 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
315 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceInput> resList) {
316 if(inputsValues != null && !inputsValues.isEmpty()){
317 for(GetInputValueDataDefinition inputData: inputsValues){
318 if(isGetInputValueForInput(inputData, inputId)){
319 prop.setComponentInstanceId(s);
320 prop.setComponentInstanceName(ciName);
328 public ComponentInstance createComponentInstance(final String containerComponentParam,
329 final String containerComponentId, final String userId,
330 final ComponentInstance resourceInstance, final boolean needLock) {
331 final User user = validateUserExists(userId);
332 validateUserNotEmpty(user, "Create component instance");
333 validateJsonBody(resourceInstance, ComponentInstance.class);
334 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
335 final org.openecomp.sdc.be.model.Component containerComponent =
336 validateComponentExists(containerComponentId, containerComponentType, null);
338 if (ModelConverter.isAtomicComponent(containerComponent)) {
339 if (log.isDebugEnabled()) {
340 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
342 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
345 validateCanWorkOnComponent(containerComponent, userId);
347 Component origComponent = null;
348 if (resourceInstance != null && containerComponentType != null) {
349 final OriginTypeEnum originType = resourceInstance.getOriginType();
350 validateInstanceName(resourceInstance);
351 if (originType == OriginTypeEnum.ServiceProxy) {
353 final Either<Component, StorageOperationStatus> serviceProxyOrigin =
354 toscaOperationFacade.getLatestByName("serviceProxy");
355 if (isServiceProxyOrigin(serviceProxyOrigin)) {
356 throw new ByActionStatusComponentException(
357 componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
359 origComponent = serviceProxyOrigin.left().value();
361 final StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
362 if (isFillProxyRes(fillProxyRes)) {
363 throw new ByActionStatusComponentException(
364 componentsUtils.convertFromStorageResponse(fillProxyRes));
367 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent,
370 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
371 validateResourceInstanceState(containerComponent, origComponent);
372 overrideFields(origComponent, resourceInstance);
373 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
375 return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
378 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
380 boolean failed = false;
383 ComponentInstance lockComponent = isNeedLock(needLock, containerComponent);
384 if (lockComponent != null) {
385 return lockComponent;
387 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
388 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
389 }catch (ComponentException e){
394 unlockComponent(failed, containerComponent);
398 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
399 resourceInstance.setComponentVersion(origComponent.getVersion());
400 resourceInstance.setIcon(origComponent.getIcon());
403 private void validateInstanceName(ComponentInstance resourceInstance) {
405 String resourceInstanceName = resourceInstance.getName();
406 if (StringUtils.isEmpty(resourceInstanceName)) {
407 log.debug("ComponentInstance name is empty");
408 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
411 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
412 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
413 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
416 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
417 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
418 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
422 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
423 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){
424 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
425 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
429 private void validateOriginAndResourceInstanceTypes(final Component containerComponent,
430 final Component origComponent,
431 final OriginTypeEnum originType) {
432 final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
433 validateOriginType(originType, resourceType);
434 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
437 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
438 switch (containerComponent.getComponentType()) {
440 if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType)) {
441 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
442 containerComponent.getComponentType().toString(), resourceType.name());
446 final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
447 if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
448 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
449 containerComponent.getComponentType().toString(), resourceType.name());
453 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
457 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
458 ResourceTypeEnum convertedOriginType;
460 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
463 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
466 if (resourceType != convertedOriginType) throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
469 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
470 switch (origComponent.getComponentType()) {
472 return ResourceTypeEnum.ServiceProxy;
474 return ((Resource) origComponent).getResourceType();
476 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
480 private ComponentInstance isNeedLock(boolean needLock, Component containerComponent) {
482 lockComponent(containerComponent, "createComponentInstance");
487 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
488 if (serviceProxyOrigin.isRight()) {
489 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
495 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
496 resourceInstance.setIsProxy(true);
497 ComponentParametersView filter = new ComponentParametersView(true);
498 filter.setIgnoreCapabilities(false);
499 filter.setIgnoreCapabiltyProperties(false);
500 filter.setIgnoreComponentInstances(false);
501 filter.setIgnoreRequirements(false);
502 filter.setIgnoreInterfaces(false);
503 filter.setIgnoreProperties(false);
504 filter.setIgnoreInputs(false);
505 Either<Component, StorageOperationStatus> serviceRes =
506 toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
507 if (serviceRes.isRight()) {
508 return serviceRes.right().value();
510 Component service = serviceRes.left().value();
511 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
512 resourceInstance.setCapabilities(capabilities);
513 Map<String, List<RequirementDefinition>> req = service.getRequirements();
514 resourceInstance.setRequirements(req);
515 Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
516 if(MapUtils.isNotEmpty(serviceInterfaces)) {
517 serviceInterfaces.forEach(resourceInstance::addInterface);
521 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
523 List<InputDefinition> serviceInputs = service.getInputs();
524 resourceInstance.setInputs(serviceInputs);
526 String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
527 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
528 int lastIndexOf = toscaResourceName.lastIndexOf('.');
529 if (lastIndexOf != -1) {
530 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
531 resourceInstance.setToscaComponentName(proxyToscaName);
533 resourceInstance.setName(name);
534 resourceInstance.setIsProxy(true);
535 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
536 resourceInstance.setSourceModelName(service.getName());
537 resourceInstance.setSourceModelUuid(service.getUUID());
538 resourceInstance.setSourceModelUid(service.getUniqueId());
539 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
540 resourceInstance.setDescription("A Proxy for Service " + service.getName());
541 resourceInstance.setComponentVersion(service.getVersion());
543 return StorageOperationStatus.OK;
546 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
548 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
549 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
550 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
552 User user = validateUserExists(userId);
554 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
556 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
558 if (ModelConverter.isAtomicComponent(containerComponent)) {
559 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
560 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
563 validateCanWorkOnComponent(containerComponent, userId);
565 boolean failed = false;
567 lockComponent(containerComponent, "createAndAssociateRIToRI");
568 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
569 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
571 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
572 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
573 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
574 associationInfo.setFromNode(resResourceInfo.getUniqueId());
576 associationInfo.setToNode(resResourceInfo.getUniqueId());
579 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo);
580 if (resultReqCapDef.isLeft()) {
581 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
582 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
583 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
584 resultOp = Either.left(resInfo);
588 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
589 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
593 }catch (ComponentException e){
597 unlockComponent(failed, containerComponent);
601 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
602 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
605 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
606 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
609 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
610 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
611 if (eitherComponent.isRight()) {
612 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
613 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
615 return eitherComponent.left().value();
618 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
619 Either<ComponentInstance, ResponseFormat> resultOp;
621 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
623 if (result.isRight()) {
624 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
625 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
628 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
629 Component updatedComponent = result.left().value().getLeft();
630 Map<String, String> existingEnvVersions = new HashMap<>();
631 // TODO existingEnvVersions ??
632 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
634 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
635 if (!updatedInstanceOptional.isPresent()) {
636 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
637 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
639 return updatedInstanceOptional.get();
642 public boolean isCloudSpecificArtifact(String artifact) {
643 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
644 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
645 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(str -> artifact.contains(str))) {
657 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
658 * @param containerComponent
659 * @param componentInstance
660 * @param originComponent
662 * @param existingEnvVersions
665 protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
667 log.debug("add artifacts to resource instance");
668 List<GroupDefinition> filteredGroups = new ArrayList<>();
669 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
670 if (ActionStatus.OK != status) {
671 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
673 StorageOperationStatus artStatus;
674 // generate heat_env if necessary
675 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
676 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
678 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
679 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
680 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
681 .getHeatArtifactDeploymentTimeout().getDefaultMinutes();
682 List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
683 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
684 String type = artifact.getArtifactType();
685 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
686 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
688 if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
689 artifact.setTimeout(defaultHeatTimeout);
693 if (artifact.checkEsIdExist()) {
694 ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
695 artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
696 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
697 existingEnvVersions);
699 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
701 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
702 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
704 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
705 listOfCloudSpecificArts.add(artifact);
707 if (CollectionUtils.isNotEmpty(filteredGroups)) {
708 filteredGroups.stream().filter(g ->
711 .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId())))
713 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
717 groupInstancesArtifacts.forEach((k,v) -> v.addAll(listOfCloudSpecificArts));
718 filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach((e) -> {
719 g.getArtifactsUuid().add(e.getArtifactUUID());
720 g.getArtifacts().add(e.getUniqueId());
722 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
723 if (artStatus != StorageOperationStatus.OK) {
724 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
725 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
728 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
729 if (result != StorageOperationStatus.OK) {
730 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
731 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
733 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
736 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
737 if (artStatus != StorageOperationStatus.OK) {
738 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
739 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
742 componentInstance.setArtifacts(originComponent.getArtifacts());
743 return ActionStatus.OK;
746 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) {
747 List<ArtifactDefinition> artifactsUid;
748 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
749 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
751 artifactsUid = new ArrayList<>();
753 artifactsUid.add(artifactDefinition);
754 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
757 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
758 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts =
759 artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
761 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
762 if (getResourceDeploymentArtifacts.isRight()) {
763 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
764 if (status != StorageOperationStatus.NOT_FOUND) {
765 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
766 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
769 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
772 if (!deploymentArtifacts.isEmpty()) {
773 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
774 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
775 if (!artifact.getValue().checkEsIdExist()) {
776 tempDeploymentArtifacts.remove(artifact.getKey());
780 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
783 return ActionStatus.OK;
786 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
787 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true);
790 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(
791 final String containerComponentParam,
792 final String containerComponentId,
793 final String componentInstanceId,
795 ComponentInstance componentInstance,
796 final boolean inTransaction,
799 validateUserExists(userId);
801 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
803 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
805 validateCanWorkOnComponent(containerComponent, userId);
806 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
807 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
808 if (validateParentStatus.isRight()) {
809 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
810 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase());
812 if (!validateParentStatus.left().value()) {
813 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
817 lockComponent(containerComponent, "updateComponentInstance");
819 Component origComponent;
820 boolean failed = false;
822 origComponent = getOriginComponentFromComponentInstance(componentInstance);
823 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
824 }catch (ComponentException e) {
829 unlockComponent(failed, containerComponent);
832 return Either.left(componentInstance);
835 // New Multiple Instance Update API
836 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
838 boolean failed = false;
840 validateUserExists(userId);
842 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
843 ComponentParametersView componentFilter = new ComponentParametersView();
844 componentFilter.disableAll();
845 componentFilter.setIgnoreUsers(false);
846 componentFilter.setIgnoreComponentInstances(false);
847 if (containerComponent == null) {
848 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
850 validateCanWorkOnComponent(containerComponent, userId);
852 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
854 for (ComponentInstance componentInstance : componentInstanceList) {
855 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
856 if (!validateParent) {
857 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
858 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
859 containerComponentId);
864 lockComponent(containerComponent, "updateComponentInstance");
867 List<ComponentInstance> updatedList = new ArrayList<>();
868 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
869 List<ComponentInstance> listForUpdate = new ArrayList<>();
870 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
871 containerComponent.setComponentInstances(componentInstanceList);
873 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
874 while (iterator.hasNext()) {
875 ComponentInstance origInst = iterator.next();
876 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
877 if (op.isPresent()) {
878 ComponentInstance updatedCi = op.get();
879 updatedCi = buildComponentInstance(updatedCi, origInst);
881 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
883 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
884 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
886 listForUpdate.add(updatedCi);
888 listForUpdate.add(origInst);
890 containerComponent.setComponentInstances(listForUpdate);
892 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
893 if (updateStatus.isRight()) {
894 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
895 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
898 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
899 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
900 if (op.isPresent()) {
901 updatedList.add(updatedInstance);
906 }catch (ComponentException e){
911 unlockComponent(failed, containerComponent);
916 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
917 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
920 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
921 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
922 return ComponentTypeEnum.SERVICE_INSTANCE;
924 return ComponentTypeEnum.RESOURCE_INSTANCE;
928 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
929 ComponentInstance componentInstance) {
931 Optional<ComponentInstance> componentInstanceOptional;
932 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
933 ComponentInstance oldComponentInstance = null;
934 boolean isNameChanged = false;
936 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
937 if (!componentInstanceOptional.isPresent()) {
938 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
939 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
941 String oldComponentName;
942 oldComponentInstance = componentInstanceOptional.get();
943 oldComponentName = oldComponentInstance.getName();
944 String newInstanceName = componentInstance.getName();
945 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName))
946 isNameChanged = true;
947 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
949 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
950 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName());
952 if(!DirectivesEnum.isValid(componentInstance.getDirectives())) {
953 final String directivesStr =
954 componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
955 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
956 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
957 oldComponentInstance.getName(), newInstanceName ,
959 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName()); }
960 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
961 if (updateRes.isRight()) {
962 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
963 updateRes.right().value());
964 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
966 // region - Update instance Groups
968 Either<StorageOperationStatus, StorageOperationStatus> result =
969 toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
970 if (result.isRight())
971 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
973 if (containerComponent instanceof Service){
974 Either<ComponentInstance, ResponseFormat> renameEither =
975 renameServiceFilter((Service) containerComponent, newInstanceName,
976 oldComponentInstance.getName());
977 if (renameEither.isRight()) {
978 throw new ByResponseFormatComponentException(renameEither.right().value());
981 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
986 String newInstanceId = updateRes.left().value().getRight();
987 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
989 if (!updatedInstanceOptional.isPresent()) {
990 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
991 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
994 return componentInstanceOptional.get();
997 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
998 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
999 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
1000 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName,
1001 componentInstance.getName());
1002 updated.forEach(fp -> {
1003 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
1004 .updateForwardingPath(containerComponent.getUniqueId(), fp);
1005 if (resultEither.isRight()){
1006 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value());
1012 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent,
1013 final String newInstanceName,
1014 final String oldInstanceName) {
1016 Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
1017 ServiceFilterUtils.getRenamedNodesFilter((Service) containerComponent,
1018 oldInstanceName, newInstanceName);
1019 for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){
1020 Either<CINodeFilterDataDefinition, StorageOperationStatus>
1021 renameEither = nodeFilterOperation.updateNodeFilter(
1022 containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
1023 if (renameEither.isRight()){
1024 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1025 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
1026 containerComponent.getName(), null));
1030 return Either.left(null);
1035 * The normalized old vf name
1036 * @param newNormailzedPrefix-
1037 * The normalized new vf name
1038 * @param qualifiedGroupInstanceName-
1039 * old Group Instance Name
1041 // modify group names
1042 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1043 if (qualifiedGroupInstanceName == null) {
1044 log.info("CANNOT change group name ");
1047 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
1048 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1049 return qualifiedGroupInstanceName;
1052 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1053 oldComponentInstance.setName(newComponentInstance.getName());
1054 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1055 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1056 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1057 if (oldComponentInstance.getGroupInstances() != null)
1058 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1059 return oldComponentInstance;
1062 public ComponentInstance deleteComponentInstance(final String containerComponentParam,
1063 final String containerComponentId,
1064 final String componentInstanceId, String userId)
1065 throws BusinessLogicException {
1067 validateUserExists(userId);
1068 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1070 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1071 validateCanWorkOnComponent(containerComponent, userId);
1073 boolean failed = false;
1074 final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1075 if (!componentInstanceOptional.isPresent()) {
1076 throw new BusinessLogicException(componentsUtils
1077 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
1079 ComponentInstance componentInstance = componentInstanceOptional.get();
1082 if (containerComponent instanceof Service || containerComponent instanceof Resource &&
1083 isVFC(componentInstance.getOriginType())) {
1085 final Either<String, StorageOperationStatus> deleteServiceFilterEither =
1086 nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId);
1087 if (deleteServiceFilterEither.isRight()) {
1088 final ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
1089 containerComponentType);
1090 janusGraphDao.rollback();
1091 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1093 final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(
1094 containerComponent, componentInstance, containerComponentType, userId);
1095 if (resultOp.isRight()) {
1096 janusGraphDao.rollback();
1097 throw new ByResponseFormatComponentException(resultOp.right().value());
1100 lockComponent(containerComponent, "deleteComponentInstance");
1101 final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1103 componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
1104 containerComponentType, deletedCompInstance);
1105 final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1106 if (ActionStatus.OK != onDeleteOperationsStatus) {
1107 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1109 } catch (final ComponentException e) {
1114 unlockComponent(failed, containerComponent);
1116 return componentInstance;
1119 public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(
1120 final Component component,
1121 final ComponentInstance componentInstance,
1122 final ComponentTypeEnum containerComponentType,
1123 final String userId) {
1125 final Set<String> componentFiltersIDsToBeDeleted =
1126 getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
1127 if (!componentFiltersIDsToBeDeleted.isEmpty()) {
1128 final Set<String> ids = component.getComponentInstances().stream()
1129 .filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
1130 .map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
1131 final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither =
1132 nodeFilterOperation.deleteNodeFilters(component, ids);
1133 if (deleteComponentNodeFiltersEither.isRight()) {
1134 final ActionStatus status = componentsUtils
1135 .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(),
1136 containerComponentType);
1137 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1139 for (final String id : ids) {
1140 final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id);
1141 if (!componentInstanceById.isPresent()) {
1142 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1144 final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
1145 final List<String> directives = componentInstanceToBeUpdated.getDirectives();
1146 componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
1147 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
1148 updateComponentInstanceMetadata(containerComponentType.getValue(), component.getUniqueId(),
1149 componentInstanceToBeUpdated.getUniqueId(), userId, componentInstanceToBeUpdated, true, false);
1150 if (componentInstanceResponseFormatEither.isRight()) {
1151 return componentInstanceResponseFormatEither;
1155 return Either.left(componentInstance);
1160 private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId,
1161 ComponentInstance componentInstance) {
1162 ComponentParametersView filter = new ComponentParametersView(true);
1163 filter.setIgnoreComponentInstances(false);
1164 Either<Component, StorageOperationStatus> componentFilterOrigin =
1165 toscaOperationFacade.getToscaElement(containerComponentId, filter);
1166 final Component component = componentFilterOrigin.left().value();
1167 final Set<String> nodesFiltersToBeDeleted = ComponentsUtils.getNodesFiltersToBeDeleted(component,
1169 return nodesFiltersToBeDeleted;
1173 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
1174 ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1175 if(containerComponentType == ComponentTypeEnum.SERVICE){
1176 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1177 if (!pathIDsToBeDeleted.isEmpty()) {
1178 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1181 return componentInstance;
1184 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
1186 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1187 if(storageStatus.isRight()) {
1188 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1190 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
1191 Sets.newHashSet(pathIdsToDelete));
1193 if(result.isRight()) {
1194 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1198 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
1199 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1200 List<String> pathIDsToBeDeleted = new ArrayList<>();
1202 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
1203 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1205 return pathIDsToBeDeleted;
1208 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1209 ComponentParametersView filter = new ComponentParametersView(true);
1210 filter.setIgnoreForwardingPath(false);
1211 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
1212 .getToscaElement(containerComponentId, filter);
1213 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1216 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
1217 String componentInstanceId){
1218 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
1219 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
1220 elementDataDefinition.getToNode()
1221 .equalsIgnoreCase(componentInstanceId));
1225 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
1226 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1227 if (deleteRes.isRight()) {
1228 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1229 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1230 throw new ByActionStatusComponentException(status, componentInstanceId);
1232 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1233 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1235 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1236 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1237 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1238 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1239 if (deleteInputsRes != StorageOperationStatus.OK) {
1240 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1241 throw new ByActionStatusComponentException(
1242 componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId);
1246 return deletedInstance;
1249 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1250 ComponentInstance foundInstance = null;
1251 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1252 if (instance.getUniqueId().equals(componentInstanceId)) {
1253 foundInstance = instance;
1254 containerComponent.getComponentInstances().remove(instance);
1258 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1259 return foundInstance;
1262 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1263 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1264 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1268 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1269 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1272 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1273 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true);
1276 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock) {
1278 validateUserExists(userId);
1280 RequirementCapabilityRelDef requirementCapabilityRelDef = null;
1282 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1284 validateCanWorkOnComponent(containerComponent, userId);
1285 boolean failed = false;
1288 lockComponent(containerComponent, "associateRIToRI");
1290 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1291 }catch (ComponentException e){
1296 unlockComponent(failed, containerComponent);
1298 return requirementCapabilityRelDef;
1301 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1303 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1305 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1307 if (result.isLeft()) {
1308 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1309 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1310 return requirementCapabilityRelDef;
1313 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1314 String fromNameOrId = "";
1315 String toNameOrId = "";
1316 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1317 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1319 toNameOrId = requirementDef.getFromNode();
1320 fromNameOrId = requirementDef.getFromNode();
1321 if (fromResult.isLeft()) {
1322 fromNameOrId = fromResult.left().value().getName();
1324 if (toResult.isLeft()) {
1325 toNameOrId = toResult.left().value().getName();
1328 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance
1329 (result.right().value(), true), fromNameOrId, toNameOrId,
1330 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1336 * @param componentId
1338 * @param requirementDefList
1339 * @param componentTypeEnum
1342 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1345 List<RequirementCapabilityRelDef> requirementDefList,
1346 ComponentTypeEnum componentTypeEnum) {
1348 validateUserExists(userId);
1349 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1350 validateCanWorkOnComponent(containerComponent, userId);
1351 boolean failed = false;
1352 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1354 lockComponent(containerComponent, "associateRIToRI");
1355 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1356 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(
1357 componentId, userId, requirementDef, containerComponent.getComponentType());
1358 delOkResult.add(requirementCapabilityRelDef);
1360 }catch (ComponentException e){
1364 unlockComponent(failed, containerComponent);
1370 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1371 validateUserExists(userId);
1373 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1374 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1376 validateCanWorkOnComponent(containerComponent, userId);
1377 boolean failed = false;
1379 lockComponent(containerComponent, "associateRIToRI");
1380 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1381 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1382 if (result.isLeft()) {
1383 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1384 return result.left().value();
1387 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1388 String fromNameOrId = "";
1389 String toNameOrId = "";
1390 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1391 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1393 toNameOrId = requirementDef.getFromNode();
1394 fromNameOrId = requirementDef.getFromNode();
1395 if (fromResult.isLeft()) {
1396 fromNameOrId = fromResult.left().value().getName();
1398 if (toResult.isLeft()) {
1399 toNameOrId = toResult.left().value().getName();
1402 throw new ByActionStatusComponentException(
1403 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1404 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1406 }catch (ComponentException e){
1410 unlockComponent(failed, containerComponent);
1414 * Allows to get relation contained in specified component according to received Id
1415 * @param componentId
1418 * @param componentTypeEnum
1421 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1423 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1425 org.openecomp.sdc.be.model.Component containerComponent = null;
1426 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1427 RequirementCapabilityRelDef foundRelation = null;
1429 validateUserExists(userId);
1430 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1431 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1432 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1433 if(foundRelation == null){
1434 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1435 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1436 resultOp = Either.right(responseFormat);
1438 if(resultOp == null){
1439 resultOp = setRelatedCapability(foundRelation, containerComponent);
1441 if(resultOp.isLeft()){
1442 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1444 } catch (Exception e) {
1445 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1446 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1451 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1452 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1453 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1454 return relationship;
1460 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1461 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1462 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1463 String instanceId = foundRelation.getFromNode();
1464 Optional<RequirementDefinition> foundRequirement;
1465 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1466 if(!instance.isPresent()){
1467 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1468 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1469 result = Either.right(responseFormat);
1472 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1473 foundRequirement = requirements.stream().filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1474 if(foundRequirement.isPresent()){
1475 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1476 result = Either.left(foundRelation);
1481 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1482 if(getfulfilledRequirementRes.isRight()){
1483 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1484 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1485 result = Either.right(responseFormat);
1487 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1491 result = Either.left(foundRelation);
1496 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1497 return req.getName().equals(relationshipInfo.getRequirement()) &&
1498 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1499 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1502 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1503 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) &&
1504 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1505 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1508 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1509 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1510 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1511 String instanceId = foundRelation.getToNode();
1512 Optional<CapabilityDefinition> foundCapability;
1513 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1514 if(!instance.isPresent()){
1515 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1516 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1517 result = Either.right(responseFormat);
1520 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1521 foundCapability = capabilities.stream().filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1522 if(foundCapability.isPresent()){
1523 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1524 result = Either.left(foundRelation);
1529 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1530 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1531 if(getfulfilledRequirementRes.isRight()){
1532 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1533 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1534 result = Either.right(responseFormat);
1536 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1540 result = Either.left(foundRelation);
1545 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1546 return cap.getName().equals(relationshipInfo.getCapability()) &&
1547 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1548 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1551 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1552 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) &&
1553 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1554 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1557 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1558 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ?
1559 currName.equals(nameFromRelationship):
1560 previousName!= null && previousName.equals(nameFromRelationship);
1563 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1564 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1565 Either<ComponentInstanceProperty, ResponseFormat> result;
1566 if (eitherAttribute.isLeft()) {
1567 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1568 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1570 result = Either.left(instanceAttribute);
1573 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1575 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1577 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1583 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1585 Either<ComponentInstanceProperty, ResponseFormat> result;
1587 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1588 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1589 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1591 if (!errorWrapper.isEmpty()) {
1592 result = Either.right(errorWrapper.getInnerElement());
1594 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1595 if (eitherAttribute.isLeft()) {
1596 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1597 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1598 result = Either.left(instanceAttribute);
1601 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1603 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1604 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1612 * Create Or Updates Attribute Instance
1614 * @param componentTypeEnum
1615 * @param componentId
1616 * @param resourceInstanceId
1621 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1622 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1623 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1625 validateUserExists(userId);
1626 if (errorWrapper.isEmpty()) {
1627 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1629 if (errorWrapper.isEmpty()) {
1630 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1632 if (errorWrapper.isEmpty()) {
1633 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1637 if (errorWrapper.isEmpty()) {
1638 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1640 result = createAttributeValue(attribute, resourceInstanceId);
1642 result = updateAttributeValue(attribute, resourceInstanceId);
1645 result = Either.right(errorWrapper.getInnerElement());
1651 if (result == null || result.isRight()) {
1652 janusGraphDao.rollback();
1654 janusGraphDao.commit();
1657 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1661 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1663 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1665 /*-------------------------------Validations---------------------------------*/
1666 validateUserExists(userId);
1668 if (componentTypeEnum == null) {
1669 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1670 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1673 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1675 if (getResourceResult.isRight()) {
1676 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1677 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1678 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1680 Component containerComponent = getResourceResult.left().value();
1682 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1683 if (containerComponent.isArchived()) {
1684 log.info("Component is archived. Component id: {}", componentId);
1685 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1687 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1688 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1691 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1692 if (resourceInstanceStatus.isRight()) {
1693 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1694 resourceInstanceId, "resource instance", "service", componentId));
1696 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1699 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1700 if (lockStatus != StorageOperationStatus.OK) {
1701 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1702 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1704 List <ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1706 for (ComponentInstanceProperty property: properties) {
1707 validateMandatoryFields(property);
1708 ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
1709 String propertyParentUniqueId = property.getParentUniqueId();
1710 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1711 if (updatedPropertyValue.isRight()) {
1712 log.error("Failed to update property object value of property: {}",
1714 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1716 Optional<CapabilityDefinition>
1717 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1718 if (capPropDefinition.isPresent()) {
1719 updatedPropertyValue
1720 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1721 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1722 capPropDefinition.get().getName()), Either::right);
1724 updatedPropertyValue.bimap(
1726 componentInstanceProperty.setValue(updatedValue);
1727 return updatePropertyOnContainerComponent(property, updatedValue,
1728 containerComponent, foundResourceInstance);
1730 updatedProperties.add(componentInstanceProperty);
1734 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1735 if (updateContainerRes.isRight()) {
1736 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1737 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1740 resultOp = Either.left(updatedProperties);
1744 if (resultOp == null || resultOp.isRight()) {
1745 janusGraphDao.rollback();
1747 janusGraphDao.commit();
1750 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1754 private void validateMandatoryFields(PropertyDataDefinition property) {
1755 if (StringUtils.isEmpty(property.getName())) {
1756 throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME);
1760 private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) {
1761 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1762 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1763 if (!instanceProperty.isPresent()) {
1764 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
1766 return instanceProperty.get();
1771 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
1772 String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1773 String capabilityType, String capabilityName) {
1774 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1775 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1776 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1777 if (actionStatus != null) {
1778 return actionStatus;
1781 return componentsUtils.getResponseFormat(ActionStatus.OK);
1784 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
1785 String newValue, Component containerComponent,
1786 ComponentInstance foundResourceInstance,
1787 String capabilityType, String capabilityName) {
1788 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1789 Either<Component, StorageOperationStatus> getComponentRes =
1790 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
1791 if(getComponentRes.isRight()) {
1792 return componentsUtils.getResponseFormat(getComponentRes.right().value());
1795 if(!PropertiesUtils.isNodeServiceProxy(getComponentRes.left().value())) {
1796 propOwner = componentInstanceUniqueId;
1798 propOwner = foundResourceInstance.getSourceModelUid();
1801 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1802 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1803 if (actionStatus != null) {
1804 return actionStatus;
1807 return componentsUtils.getResponseFormat(ActionStatus.OK);
1810 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
1811 Component containerComponent,
1812 ComponentInstance foundResourceInstance,
1813 String capabilityType, String capabilityName,
1814 String componentInstanceUniqueId) {
1815 Map<String, List<CapabilityDefinition>> capabilities =
1816 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
1817 List<CapabilityDefinition> capPerType =
1818 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1819 Optional<CapabilityDefinition> cap =
1820 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1821 if (cap.isPresent()) {
1822 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1823 if (capProperties != null) {
1824 Optional<ComponentInstanceProperty> instanceProperty =
1825 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1826 StorageOperationStatus status;
1827 if (instanceProperty.isPresent()) {
1828 String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
1829 instanceProperty.get().setValue(newValue);
1830 List<String> path = new ArrayList<>();
1831 path.add(componentInstanceUniqueId);
1833 instanceProperty.get().setPath(path);
1834 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
1835 componentInstanceUniqueId, capKey, instanceProperty.get());
1836 if (status != StorageOperationStatus.OK) {
1837 ActionStatus actionStatus =
1838 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1839 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1842 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1849 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1850 StorageOperationStatus status;
1851 instanceProperty.setValue(newValue);
1852 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
1853 if (status != StorageOperationStatus.OK) {
1854 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1855 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1857 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1858 return componentsUtils.getResponseFormat(ActionStatus.OK);
1861 private <T extends PropertyDefinition> Either<String,ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
1862 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1863 if (allDataTypesEither.isRight()) {
1864 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1865 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1866 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1868 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1869 String propertyType = property.getType();
1870 String innerType = getInnerType(property);
1872 // Specific Update Logic
1873 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
1874 if (isValid.isRight()) {
1875 Boolean res = isValid.right().value();
1877 log.error("Invalid value {} of property {} ", newValue, property.getName());
1878 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1881 Object object = isValid.left().value();
1882 if (object != null) {
1883 newValue = object.toString();
1886 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType))
1887 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1888 return Either.left(newValue);
1891 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes, String innerType, String propertyType) {
1893 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1894 if (pair.getRight() != null && !pair.getRight()) {
1895 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1902 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1903 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1904 if (allDataTypesEither.isRight()) {
1905 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1906 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1907 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1909 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1910 String innerType = null;
1911 String propertyType = property.getType();
1912 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1913 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1915 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1916 SchemaDefinition def = property.getSchema();
1918 log.debug("Schema doesn't exists for property of type {}", type);
1919 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1921 PropertyDataDefinition propDef = def.getProperty();
1922 if (propDef == null) {
1923 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1924 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1926 innerType = propDef.getType();
1928 // Specific Update Logic
1929 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1930 String newValue = property.getValue();
1931 if (isValid.isRight()) {
1932 Boolean res = isValid.right().value();
1934 log.debug("validate and update property value has failed with value: {}", property.getValue());
1935 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
1938 Object object = isValid.left().value();
1939 if (object != null) {
1940 newValue = object.toString();
1944 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1945 if (pair.getRight() != null && pair.getRight() == false) {
1946 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1947 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1950 return Either.left(newValue);
1953 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1954 StorageOperationStatus status;
1955 input.setValue(newValue);
1956 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1957 if (status != StorageOperationStatus.OK) {
1958 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1959 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1961 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1962 return componentsUtils.getResponseFormat(ActionStatus.OK);
1965 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1967 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1969 validateUserExists(userId);
1971 if (componentTypeEnum == null) {
1972 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1973 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1976 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1978 if (getResourceResult.isRight()) {
1979 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1980 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1981 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1983 Component containerComponent = getResourceResult.left().value();
1985 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1986 if (containerComponent.isArchived()) {
1987 log.info("Component is archived. Component id: {}", componentId);
1988 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1990 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1991 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1994 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1995 if (resourceInstanceStatus.isRight()) {
1996 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1997 resourceInstanceId, "resource instance", "service", componentId));
2000 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2003 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2004 if (lockStatus != StorageOperationStatus.OK) {
2005 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2006 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2008 List <ComponentInstanceInput> updatedInputs = new ArrayList<>();
2010 for (ComponentInstanceInput input: inputs) {
2011 validateMandatoryFields(input);
2012 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
2013 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
2014 if (validatedInputValue.isRight()){
2015 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2017 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance);
2018 updatedInputs.add(componentInstanceInput);
2020 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2021 if (updateContainerRes.isRight()) {
2022 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2023 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2026 resultOp = Either.left(updatedInputs);
2030 if (resultOp == null || resultOp.isRight()) {
2031 janusGraphDao.rollback();
2033 janusGraphDao.commit();
2036 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2041 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) {
2042 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2043 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2044 if (!instanceInput.isPresent()) {
2045 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2047 return instanceInput.get();
2050 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) {
2052 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2054 validateUserExists(userId);
2056 if (componentTypeEnum == null) {
2057 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2058 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2062 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2063 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2064 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2068 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2069 if (lockStatus != StorageOperationStatus.OK) {
2070 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2071 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2075 String propertyValueUid = property.getValueUniqueUid();
2077 if (propertyValueUid == null) {
2079 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2081 if (counterRes.isRight()) {
2082 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2083 StorageOperationStatus status = counterRes.right().value();
2084 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2085 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2087 Integer index = counterRes.left().value();
2088 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2090 if (result.isLeft()) {
2091 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2092 ComponentInstanceProperty instanceProperty = result.left().value();
2094 resultOp = Either.left(instanceProperty);
2097 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2099 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2101 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2105 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2107 if (result.isLeft()) {
2108 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2109 ComponentInstanceProperty instanceProperty = result.left().value();
2111 resultOp = Either.left(instanceProperty);
2114 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2116 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2118 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2121 if (resultOp.isLeft()) {
2122 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2123 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2124 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2126 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2133 if (resultOp == null || resultOp.isRight()) {
2134 janusGraphDao.rollback();
2136 janusGraphDao.commit();
2139 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2144 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
2146 validateUserExists(userId);
2148 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2150 if (componentTypeEnum == null) {
2151 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2152 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2156 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2157 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2158 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2162 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2163 if (lockStatus != StorageOperationStatus.OK) {
2164 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2165 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2169 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2171 if (result.isLeft()) {
2172 log.debug("Property value {} was removed from graph.", propertyValueId);
2173 ComponentInstanceProperty instanceProperty = result.left().value();
2175 resultOp = Either.left(instanceProperty);
2179 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2181 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2183 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2189 if (resultOp == null || resultOp.isRight()) {
2190 janusGraphDao.rollback();
2192 janusGraphDao.commit();
2195 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2200 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2202 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2203 Component component;
2204 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2205 if (getComponentRes.isRight()) {
2206 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2207 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2208 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2210 component = getComponentRes.left().value();
2211 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2212 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2213 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2214 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2216 if (component.isArchived() == true){
2217 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2218 throw new ByActionStatusComponentException(actionStatus, component.getName());
2223 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2224 String containerComponentId,
2225 String componentInstanceId,
2226 ComponentInstance newComponentInstance) {
2227 Either<Set<String>, ResponseFormat> resultOp;
2228 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2229 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2232 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2234 //Fetch current component instance
2235 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2236 getResourceInstanceById(containerComponent, componentInstanceId);
2237 if (eitherResourceInstance.isRight()) {
2238 resultOp = Either.right(componentsUtils.getResponseFormat(
2239 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2242 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2244 //Check whether new componentInstance exists
2245 String resourceId = newComponentInstance.getComponentUid();
2246 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2247 if (componentExistsRes.isRight()) {
2248 log.debug("Failed to find resource {}", resourceId);
2249 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2250 (componentExistsRes.right().value()), resourceId));
2252 } else if (!componentExistsRes.left().value()) {
2253 log.debug("The resource {} not found ", resourceId);
2254 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2258 //Fetch component using new component instance uid
2259 Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance);
2260 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2261 currentResourceInstance, updatedContainerComponent);
2262 resultOp=Either.left(toDeleteForwardingPaths);
2267 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2268 Component updatedContainerComponent) {
2269 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2270 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2272 Service service = (Service) containerComponent;
2273 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2275 return forwardingPathUtils.
2276 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2279 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2280 ComponentParametersView componentParametersView = new ComponentParametersView();
2281 componentParametersView.setIgnoreCapabiltyProperties(false);
2282 componentParametersView.setIgnoreForwardingPath(false);
2283 return componentParametersView;
2286 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2288 User user = validateUserExists(userId);
2289 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2290 ComponentParametersView componentParametersView = new ComponentParametersView();
2291 componentParametersView.setIgnoreCapabiltyProperties(false);
2293 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2295 validateCanWorkOnComponent(containerComponent, userId);
2297 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2298 if (resourceInstanceStatus.isRight()) {
2299 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId);
2302 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2304 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2307 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
2308 ComponentInstance currentResourceInstance,
2309 ComponentInstance newComponentInstance,
2311 final ComponentTypeEnum containerComponentType) {
2312 boolean failed = false;
2313 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2316 lockComponent(containerComponent, "changeComponentInstanceVersion");
2317 String containerComponentId = containerComponent.getUniqueId();
2318 String componentInstanceId = currentResourceInstance.getUniqueId();
2319 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2320 return currentResourceInstance;
2322 String resourceId = newComponentInstance.getComponentUid();
2324 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
2325 .validateComponentExists(resourceId);
2326 if (componentExistsRes.isRight()) {
2327 StorageOperationStatus errorStatus = componentExistsRes.right().value();
2329 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
2330 throw new ByActionStatusComponentException(
2331 componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
2332 } else if (!componentExistsRes.left().value()) {
2333 log.debug("The resource {} not found ", resourceId);
2334 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2337 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2339 DataForMergeHolder dataHolder = compInstMergeDataBL
2340 .saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2341 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
2342 containerComponentType);
2344 if (resResourceInfo == null) {
2345 log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
2346 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2348 Component origComponent = null;
2349 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2350 if (originType == OriginTypeEnum.ServiceProxy) {
2351 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
2352 .getLatestByName("serviceProxy");
2353 if (isServiceProxyOrigin(serviceProxyOrigin)) {
2354 throw new ByActionStatusComponentException(
2355 componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2357 origComponent = serviceProxyOrigin.left().value();
2359 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2361 if (isFillProxyRes(fillProxyRes)) {
2362 throw new ByActionStatusComponentException(
2363 componentsUtils.convertFromStorageResponse(fillProxyRes));
2365 newComponentInstance.setOriginType(originType);
2367 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2368 newComponentInstance.setName(resResourceInfo.getName());
2371 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2372 newComponentInstance.setPosX(resResourceInfo.getPosX());
2373 newComponentInstance.setPosY(resResourceInfo.getPosY());
2374 newComponentInstance.setDescription(resResourceInfo.getDescription());
2376 ComponentInstance updatedComponentInstance = createComponentInstanceOnGraph(containerComponent,
2377 origComponent, newComponentInstance, user);
2378 dataHolder.setCurrInstanceNode(origComponent);
2379 Component mergeStatusEither = compInstMergeDataBL
2380 .mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId,
2381 newComponentInstance.getUniqueId());
2383 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
2384 .doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2385 if (postChangeVersionResult != ActionStatus.OK) {
2386 throw new ByActionStatusComponentException(postChangeVersionResult);
2389 ComponentParametersView filter = new ComponentParametersView(true);
2390 filter.setIgnoreComponentInstances(false);
2391 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade
2392 .getToscaElement(containerComponentId, filter);
2393 if (updatedComponentRes.isRight()) {
2394 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2395 ActionStatus actionStatus = componentsUtils
2396 .convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2397 log.debug("Component with id {} was not found", containerComponentId);
2398 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2400 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
2401 updatedComponentInstance.getUniqueId());
2402 if (resourceInstanceStatus.isRight()) {
2403 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
2404 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
2406 return resourceInstanceStatus.left().value();
2408 } catch (ComponentException e) {
2412 unlockComponent(failed, containerComponent);
2416 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
2417 if (fillProxyRes != StorageOperationStatus.OK) {
2418 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2425 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2426 Component containerComponent = null;
2428 boolean failed = false;
2430 validateUserExists(userId);
2431 validateComponentType(containerComponentTypeParam);
2433 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2434 if (validateContainerComponentExists.isRight()) {
2435 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
2437 containerComponent = validateContainerComponentExists.left().value();
2439 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2440 if (resourceInstanceStatus.isRight()) {
2441 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
2444 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2445 if (CollectionUtils.isEmpty(instanceProperties)) {
2446 instanceProperties = new ArrayList<>();
2448 return instanceProperties;
2449 }catch (ComponentException e){
2453 unlockComponent(failed, containerComponent);
2457 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2458 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2460 if (counterRes.isRight()) {
2461 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2462 StorageOperationStatus status = counterRes.right().value();
2463 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2464 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2466 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2472 * updates componentInstance modificationTime
2474 * @param componentInstance
2475 * @param componentInstanceType
2476 * @param modificationTime
2477 * @param inTransaction
2480 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2481 Either<ComponentInstanceData, ResponseFormat> result;
2482 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2484 if (updateComponentInstanceRes.isRight()) {
2485 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2486 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2488 result = Either.left(updateComponentInstanceRes.left().value());
2493 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2494 // TODO Add implementation
2495 return Either.left(new ComponentInstance());
2498 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2499 // TODO Add implementation
2500 return Either.left(new ComponentInstance());
2503 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2504 // TODO Add implementation
2505 return Either.left(new ComponentInstance());
2508 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2509 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2512 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2514 Either<ComponentInstance, StorageOperationStatus> result = null;
2515 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2516 Optional<ComponentInstance> foundInstance = null;
2517 if (CollectionUtils.isEmpty(instances)) {
2518 result = Either.right(StorageOperationStatus.NOT_FOUND);
2520 if (result == null) {
2521 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2522 if (!foundInstance.isPresent()) {
2523 result = Either.right(StorageOperationStatus.NOT_FOUND);
2526 if (result == null) {
2527 result = Either.left(foundInstance.get());
2532 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2534 Long creationDate = origInstanceForUpdate.getCreationTime();
2536 Long modificationTime = System.currentTimeMillis();
2537 resourceInstanceForUpdate.setCreationTime(creationDate);
2538 resourceInstanceForUpdate.setModificationTime(modificationTime);
2540 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2542 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2543 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2546 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2548 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2549 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2551 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2552 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2554 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2555 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2557 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2558 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2560 if (resourceInstanceForUpdate.getOriginType() == null) {
2561 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2563 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2564 resourceInstanceForUpdate.setIsProxy(true);
2565 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2566 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2568 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2569 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2571 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2572 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2574 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2575 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2577 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
2578 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
2580 return resourceInstanceForUpdate;
2583 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2584 * @param containerComponentType
2585 * @param containerComponentId
2586 * @param componentInstanceUniqueId
2587 * @param capabilityType
2588 * @param capabilityName
2593 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2595 Component containerComponent = null;
2597 List<ComponentInstanceProperty> resultOp = null;
2599 validateUserExists(userId);
2600 validateComponentType(containerComponentType);
2601 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
2602 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left().on(this::componentInstanceException);
2603 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.getCapabilities());
2604 } catch(StorageException e){
2605 unlockRollbackWithException(containerComponent, e);
2606 } catch (ComponentException e) {
2607 unlockRollbackWithException(containerComponent, e);
2608 } catch (Exception e){
2609 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
2611 unlockWithCommit(containerComponent);
2615 private List<ComponentInstanceProperty> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2616 CapabilityDefinition foundCapability;
2617 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2618 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2619 if (capabilitiesPerType != null) {
2620 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2621 if (capabilityOpt.isPresent()) {
2622 foundCapability = capabilityOpt.get();
2623 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
2627 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2630 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2632 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
2634 .on(this::componentInstancePropertyListException);
2635 } catch(Exception e){
2636 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2637 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
2641 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2642 List<ComponentInstanceProperty> properties, String userId) {
2643 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2645 validateUserExists(userId);
2646 if (componentTypeEnum == null) {
2647 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2648 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2650 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2652 if (getResourceResult.isRight()) {
2653 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2654 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2656 Component containerComponent = getResourceResult.left().value();
2658 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2659 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2660 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2662 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2663 if (resourceInstanceStatus.isRight()) {
2664 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2666 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2668 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2669 if (lockStatus != StorageOperationStatus.OK) {
2670 log.debug("Failed to lock component {}", containerComponentId);
2671 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2675 for (ComponentInstanceProperty property : properties) {
2676 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
2677 newPropertyValueEither.bimap(updatedValue ->
2678 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2681 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2683 if (updateContainerRes.isRight()) {
2684 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2685 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2688 resultOp = Either.left(properties);
2692 if (resultOp == null || resultOp.isRight()) {
2693 janusGraphDao.rollback();
2695 janusGraphDao.commit();
2698 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2702 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2703 String containerComponentId,
2704 String componentInstanceId,
2707 Map<String, ComponentInstance> resultMap = new HashMap<>();
2708 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2709 if (getOrigComponent.isRight()) {
2710 log.error("Failed to get the original component information");
2711 return Either.right(componentsUtils.getResponseFormat(
2712 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2715 Component origComponent = getOrigComponent.left().value();
2718 lockComponent(origComponent, "copyComponentInstance");
2720 } catch (ComponentException e) {
2721 log.error("destComponentInstance's data is {}", origComponent.toString());
2722 return Either.right(componentsUtils.getResponseFormat(
2723 ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString()));
2726 boolean failed = false;
2727 ComponentInstance actionResponse = null;
2730 actionResponse = createComponentInstance(
2731 "services", containerComponentId, userId, inputComponentInstance, false);
2733 } catch (ComponentException e) {
2738 // on failure of the create instance unlock the resource and rollback the transaction.
2739 if (null == actionResponse || failed) {
2740 janusGraphDao.rollback();
2741 log.error("Failed to copy the component instance to the canvas");
2743 unlockComponent(failed, origComponent);
2745 return Either.right(componentsUtils.getResponseFormat(
2746 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2750 Either<String, ResponseFormat> resultOp = null;
2753 ComponentInstance destComponentInstance = actionResponse;
2754 log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2757 resultOp = deepCopyComponentInstance(
2758 origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2760 resultMap.put("componentInstance", destComponentInstance);
2764 if (resultOp == null || resultOp.isRight()) {
2765 unlockComponent(true, origComponent);
2766 janusGraphDao.rollback();
2767 log.error("Failed to deep copy component instance");
2768 return Either.right(componentsUtils.getResponseFormat(
2769 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2771 unlockComponent(false, origComponent);
2772 janusGraphDao.commit();
2773 log.debug("Success trasaction commit");
2777 return Either.left(resultMap);
2780 private Either<String, ResponseFormat> deepCopyComponentInstance(
2781 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2782 ComponentInstance destComponentInstance, String userId) {
2784 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2785 if (getDestComponent.isRight()) {
2786 log.error("Failed to get the dest component information");
2787 return Either.right(componentsUtils.getResponseFormat(
2788 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2791 Component destComponent = getDestComponent.left().value();
2793 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2794 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2795 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2796 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2797 return Either.right(componentsUtils.getResponseFormat(
2798 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2801 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2802 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2803 if (copyComponentInstanceWithAttributes.isRight()) {
2804 log.error("Failed to copy component instance with attributes as part of deep copy");
2805 return Either.right(componentsUtils.getResponseFormat(
2806 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2808 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2811 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2812 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2813 ComponentInstance destComponentInstance, String userId) {
2814 log.debug("start to copy ComponentInstance with properties and inputs");
2816 List<ComponentInstanceProperty> sourcePropList = null;
2817 if (sourceComponent.getComponentInstancesProperties() != null
2818 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2819 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2820 log.debug("sourcePropList");
2823 List<ComponentInstanceProperty> destPropList = null;
2824 String destComponentInstanceId = destComponentInstance.getUniqueId();
2825 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2826 if (destComponent.getComponentInstancesProperties() != null
2827 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2828 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2829 log.debug("destPropList {}");
2832 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2834 if (null != destPropList && null != sourcePropList) {
2835 log.debug("start to set property and attribute");
2836 for (ComponentInstanceProperty destProp : destPropList) {
2837 String destPropertyName = destProp.getName();
2838 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2839 if (!destPropertyName.equals(sourceProp.getName())) {
2842 log.debug("now set property");
2843 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2844 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2845 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2847 destProp.setValue(sourceProp.getValue());
2848 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2849 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2850 if (updatePropertyValueEither.isRight()) {
2851 log.error("Failed to copy the property {}", destPropertyName);
2852 return Either.right(componentsUtils.getResponseFormat(
2853 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2858 log.debug("Now start to update inputs");
2860 if (sourceProp.getGetInputValues() != null) {
2861 if (sourceProp.getGetInputValues().size() < 1) {
2862 log.debug("property is return from input, set by man");
2865 log.debug("Now starting to copy the {} property", destPropertyName);
2867 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2868 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2869 if (getSourceInputDefaultValue.isRight()) {
2870 return Either.right(getSourceInputDefaultValue.right().value());
2872 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2877 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2880 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
2881 Component destComponent,
2882 String sourceComponentInstanceId,
2883 ComponentInstance destComponentInstance,
2885 String destComponentInstanceId = destComponentInstance.getUniqueId();
2887 log.info("start to copy component instance with attributes");
2889 List<ComponentInstanceAttribute> sourceAttributeList = null;
2890 if (sourceComponent.getComponentInstancesAttributes() != null
2891 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
2892 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
2893 log.info("sourceAttributes {}");
2896 List<ComponentInstanceAttribute> destAttributeList = null;
2897 if (destComponent.getComponentInstancesAttributes() != null
2898 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
2899 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
2900 log.info("destAttributeList {}");
2902 if (null != sourceAttributeList && null != destAttributeList) {
2903 log.info("set attribute");
2905 for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
2906 String sourceAttributeName = sourceAttribute.getName();
2907 for (ComponentInstanceAttribute destAttribute : destAttributeList) {
2908 if (sourceAttributeName.equals(destAttribute.getName())) {
2909 // if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
2910 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
2912 sourceAttribute.setUniqueId(
2913 UniqueIdBuilder.buildResourceInstanceUniuqeId(
2914 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
2916 Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither =
2917 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
2918 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
2920 if (updateAttributeValueEither.isRight()) {
2921 log.error("Failed to copy the attribute");
2922 return Either.right(componentsUtils
2923 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
2924 "Failed to paste component instance to the canvas, attribute copy"));
2933 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2936 private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
2938 String resourceInstanceId,
2939 ComponentInstanceAttribute attribute,
2942 Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
2944 validateUserExists(userId);
2946 if (componentTypeEnum == null) {
2947 BeEcompErrorManager.getInstance().logInvalidInputError(
2948 "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2949 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2953 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2955 if (getResourceResult.isRight()) {
2956 log.info("Failed to retrieve component id {}", componentId);
2957 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2961 Component containerComponent = getResourceResult.left().value();
2963 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2965 if (resourceInstanceStatus.isRight()) {
2966 resultOp = Either.right(componentsUtils.getResponseFormat(
2967 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
2971 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2974 String propertyType = attribute.getType();
2975 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2976 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
2978 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2979 SchemaDefinition def = attribute.getSchema();
2981 log.info("Schema doesn't exists for attribute of type {}", type);
2982 return Either.right(componentsUtils.getResponseFormat(
2983 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2985 PropertyDataDefinition propDef = def.getProperty();
2986 if (propDef == null) {
2987 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
2988 return Either.right(componentsUtils.getResponseFormat(
2989 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2993 List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
2994 Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
2995 StorageOperationStatus status;
2997 if (instanceAttribute.isPresent()) {
2998 log.info("updateComponentInstanceAttribute");
2999 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3001 log.info("addComponentInstanceAttribute");
3002 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3004 if (status != StorageOperationStatus.OK) {
3005 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3006 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3009 List<String> path = new ArrayList<>();
3010 path.add(foundResourceInstance.getUniqueId());
3011 attribute.setPath(path);
3013 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3014 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3015 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3017 if (updateContainerRes.isRight()) {
3018 ActionStatus actionStatus = componentsUtils.
3019 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3020 resultOp = Either.right(componentsUtils.
3021 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3024 resultOp = Either.left(attribute);
3028 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3029 String componentInstanceId,
3030 ComponentInstanceProperty property) {
3031 Either<String, ResponseFormat> resultOp;
3032 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3034 if (getComponent.isRight()) {
3035 log.error("Failed to get the component information");
3036 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3037 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3040 Component containerComponent = getComponent.left().value();
3042 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3043 containerComponent, componentInstanceId, property);
3044 if (status != StorageOperationStatus.OK) {
3045 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3046 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3050 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3051 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3053 if (updateContainerRes.isRight()) {
3054 ActionStatus actionStatus = componentsUtils.
3055 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3056 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3060 return Either.left("Update OK");
3063 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3064 List<InputDefinition> inputList = component.getInputs();
3065 for (InputDefinition input : inputList) {
3066 if (input.getUniqueId().equals(inputId)) {
3067 if (input.getDefaultValue() == null) {
3068 log.debug("The input's default value is null");
3069 return Either.left(null);
3071 return Either.left(input.getDefaultValue());
3074 log.error("The input's default value with id {} is not found", inputId);
3075 return Either.right(componentsUtils.getResponseFormat(
3076 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3080 * Method to delete selected nodes and edges on composition page
3081 * @param containerComponentType
3082 * @param componentId
3083 * @param componentInstanceIdList
3087 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3089 List<String> componentInstanceIdList,
3092 List<String> deleteErrorIds = new ArrayList<>();
3093 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3094 validateUserExists(userId);
3095 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null);
3097 boolean failed = false;
3099 lockComponent(containerComponent, "batchDeleteComponentInstance");
3100 for (String eachInstanceId : componentInstanceIdList) {
3101 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3102 containerComponent, containerComponentType, componentId, eachInstanceId);
3103 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3104 if (actionResponse.isRight()) {
3105 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3106 deleteErrorIds.add(eachInstanceId);
3109 //sending the ids of the error nodes that were not deleted to UI
3110 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3111 return deleteErrorMap;
3112 }catch (ComponentException e){
3116 unlockComponent(failed, containerComponent);
3120 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3121 String containerComponentType,
3122 String containerComponentId,
3123 String componentInstanceId) {
3125 ComponentInstance resultOp;
3126 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3128 boolean failed = false;
3130 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3131 log.info("Successfully deleted instance with id {}", componentInstanceId);
3132 return Either.left(resultOp);
3134 catch (ComponentException e){
3135 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3136 return Either.right(new ResponseFormat());
3140 public boolean isVFC(final OriginTypeEnum originTypeEnum) {
3141 return OriginTypeEnum.VFC.equals(originTypeEnum);
3144 public void validateUser(final String userId) {
3145 final User user = userValidations.validateUserExists(userId);
3146 userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));