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 java.util.stream.Collectors.joining;
24 import static java.util.stream.Collectors.toList;
25 import static java.util.stream.Collectors.toMap;
26 import static java.util.stream.Collectors.toSet;
27 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
28 import static org.apache.commons.collections.MapUtils.isEmpty;
29 import static org.apache.commons.collections.MapUtils.isNotEmpty;
30 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
31 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
32 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
33 import static org.openecomp.sdc.common.api.Constants.DEFAULT_GROUP_VF_MODULE;
35 import com.google.common.annotations.VisibleForTesting;
36 import fj.data.Either;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.EnumMap;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.ListIterator;
47 import java.util.Map.Entry;
48 import java.util.Optional;
50 import java.util.function.Function;
51 import java.util.regex.Pattern;
52 import java.util.stream.Collectors;
53 import javax.servlet.ServletContext;
54 import org.apache.commons.codec.binary.Base64;
55 import org.apache.commons.collections.CollectionUtils;
56 import org.apache.commons.collections.MapUtils;
57 import org.apache.commons.collections4.ListUtils;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.commons.lang3.tuple.ImmutablePair;
60 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
61 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
62 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
63 import org.openecomp.sdc.be.components.csar.CsarInfo;
64 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
65 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
66 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
67 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
68 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
69 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
70 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
71 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
72 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
73 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
74 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
75 import org.openecomp.sdc.be.components.merge.TopologyComparator;
76 import org.openecomp.sdc.be.components.merge.property.PropertyDataValueMergeBusinessLogic;
77 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
78 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
79 import org.openecomp.sdc.be.components.property.PropertyConstraintsUtils;
80 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
81 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
82 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
83 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
84 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
85 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
86 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
87 import org.openecomp.sdc.be.config.BeEcompErrorManager;
88 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
89 import org.openecomp.sdc.be.config.ConfigurationManager;
90 import org.openecomp.sdc.be.dao.api.ActionStatus;
91 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
92 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
93 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
94 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
95 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
96 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
97 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
98 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
99 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
100 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
101 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
102 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
103 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
104 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
105 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
106 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
107 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
108 import org.openecomp.sdc.be.impl.ComponentsUtils;
109 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
110 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
111 import org.openecomp.sdc.be.model.ArtifactDefinition;
112 import org.openecomp.sdc.be.model.AttributeDefinition;
113 import org.openecomp.sdc.be.model.CapabilityDefinition;
114 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
115 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
116 import org.openecomp.sdc.be.model.Component;
117 import org.openecomp.sdc.be.model.ComponentInstance;
118 import org.openecomp.sdc.be.model.ComponentInstanceInput;
119 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
120 import org.openecomp.sdc.be.model.ComponentParametersView;
121 import org.openecomp.sdc.be.model.DataTypeDefinition;
122 import org.openecomp.sdc.be.model.GroupDefinition;
123 import org.openecomp.sdc.be.model.InputDefinition;
124 import org.openecomp.sdc.be.model.InterfaceDefinition;
125 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
126 import org.openecomp.sdc.be.model.LifecycleStateEnum;
127 import org.openecomp.sdc.be.model.NodeTypeInfo;
128 import org.openecomp.sdc.be.model.Operation;
129 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
130 import org.openecomp.sdc.be.model.PolicyDefinition;
131 import org.openecomp.sdc.be.model.PropertyDefinition;
132 import org.openecomp.sdc.be.model.RelationshipImpl;
133 import org.openecomp.sdc.be.model.RelationshipInfo;
134 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
135 import org.openecomp.sdc.be.model.RequirementDefinition;
136 import org.openecomp.sdc.be.model.Resource;
137 import org.openecomp.sdc.be.model.UploadArtifactInfo;
138 import org.openecomp.sdc.be.model.UploadCapInfo;
139 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
140 import org.openecomp.sdc.be.model.UploadInfo;
141 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
142 import org.openecomp.sdc.be.model.UploadPropInfo;
143 import org.openecomp.sdc.be.model.UploadReqInfo;
144 import org.openecomp.sdc.be.model.UploadResourceInfo;
145 import org.openecomp.sdc.be.model.User;
146 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
147 import org.openecomp.sdc.be.model.category.CategoryDefinition;
148 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
149 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
150 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
151 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
152 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
153 import org.openecomp.sdc.be.model.operations.StorageException;
154 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
155 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
156 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
157 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
158 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
159 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
160 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
161 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
162 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
163 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
164 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
165 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
166 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
167 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
168 import org.openecomp.sdc.be.tosca.CsarUtils;
169 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
170 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
171 import org.openecomp.sdc.be.user.UserBusinessLogic;
172 import org.openecomp.sdc.be.utils.CommonBeUtils;
173 import org.openecomp.sdc.be.utils.TypeUtils;
174 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
175 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
176 import org.openecomp.sdc.common.api.Constants;
177 import org.openecomp.sdc.common.datastructure.Wrapper;
178 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
179 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
180 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
181 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
182 import org.openecomp.sdc.common.log.enums.StatusCode;
183 import org.openecomp.sdc.common.log.wrappers.Logger;
184 import org.openecomp.sdc.common.util.GeneralUtility;
185 import org.openecomp.sdc.common.util.ValidationUtils;
186 import org.openecomp.sdc.exception.ResponseFormat;
187 import org.springframework.beans.factory.annotation.Autowired;
188 import org.springframework.context.annotation.Lazy;
189 import org.springframework.web.context.WebApplicationContext;
190 import org.yaml.snakeyaml.DumperOptions;
191 import org.yaml.snakeyaml.Yaml;
193 @org.springframework.stereotype.Component("resourceBusinessLogic")
194 public class ResourceBusinessLogic extends ComponentBusinessLogic {
196 private static final String DELETE_RESOURCE = "Delete Resource";
197 private static final String IN_RESOURCE = " in resource {} ";
198 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
199 public static final String INITIAL_VERSION = "0.1";
200 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
201 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
202 private static final String CREATE_RESOURCE = "Create Resource";
203 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
204 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
205 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
206 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
207 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
208 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
211 private IInterfaceLifecycleOperation interfaceTypeOperation;
212 private LifecycleBusinessLogic lifecycleBusinessLogic;
214 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
215 private final ResourceImportManager resourceImportManager;
216 private final InputsBusinessLogic inputsBusinessLogic;
217 private final CompositionBusinessLogic compositionBusinessLogic;
218 private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
219 private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
220 private final MergeInstanceUtils mergeInstanceUtils;
221 private final UiComponentDataConverter uiComponentDataConverter;
222 private final CsarBusinessLogic csarBusinessLogic;
223 private final PropertyBusinessLogic propertyBusinessLogic;
224 private final PolicyBusinessLogic policyBusinessLogic;
227 public ResourceBusinessLogic(IElementOperation elementDao,
228 IGroupOperation groupOperation,
229 IGroupInstanceOperation groupInstanceOperation,
230 IGroupTypeOperation groupTypeOperation,
231 GroupBusinessLogic groupBusinessLogic,
232 InterfaceOperation interfaceOperation,
233 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
234 ArtifactsBusinessLogic artifactsBusinessLogic,
235 ComponentInstanceBusinessLogic componentInstanceBusinessLogic, @Lazy ResourceImportManager resourceImportManager,
236 InputsBusinessLogic inputsBusinessLogic, CompositionBusinessLogic compositionBusinessLogic,
237 ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
238 CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic, MergeInstanceUtils mergeInstanceUtils,
239 UiComponentDataConverter uiComponentDataConverter, CsarBusinessLogic csarBusinessLogic,
240 ArtifactsOperations artifactToscaOperation, PropertyBusinessLogic propertyBusinessLogic,
241 ComponentContactIdValidator componentContactIdValidator,
242 ComponentNameValidator componentNameValidator, ComponentTagsValidator componentTagsValidator,
243 ComponentValidator componentValidator,
244 ComponentIconValidator componentIconValidator,
245 ComponentProjectCodeValidator componentProjectCodeValidator,
246 ComponentDescriptionValidator componentDescriptionValidator, PolicyBusinessLogic policyBusinessLogic) {
247 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
248 interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation,
249 componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
250 componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
251 this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
252 this.resourceImportManager = resourceImportManager;
253 this.inputsBusinessLogic = inputsBusinessLogic;
254 this.compositionBusinessLogic = compositionBusinessLogic;
255 this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
256 this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
257 this.mergeInstanceUtils = mergeInstanceUtils;
258 this.uiComponentDataConverter = uiComponentDataConverter;
259 this.csarBusinessLogic = csarBusinessLogic;
260 this.propertyBusinessLogic = propertyBusinessLogic;
261 this.policyBusinessLogic = policyBusinessLogic;
265 private ICapabilityTypeOperation capabilityTypeOperation;
268 private TopologyComparator topologyComparator;
271 private ComponentValidator componentValidator;
274 private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
277 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
279 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
280 return lifecycleBusinessLogic;
284 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
285 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
289 protected void setComponentValidator(ComponentValidator componentValidator) {
290 this.componentValidator = componentValidator;
293 public IElementOperation getElementDao() {
297 public void setElementDao(IElementOperation elementDao) {
298 this.elementDao = elementDao;
301 public UserBusinessLogic getUserAdmin() {
302 return this.userAdmin;
306 public void setUserAdmin(UserBusinessLogic userAdmin) {
307 this.userAdmin = userAdmin;
310 public ComponentsUtils getComponentsUtils() {
311 return this.componentsUtils;
315 public void setComponentsUtils(ComponentsUtils componentsUtils) {
316 this.componentsUtils = componentsUtils;
319 public ArtifactsBusinessLogic getArtifactsManager() {
320 return artifactsBusinessLogic;
323 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
324 this.artifactsBusinessLogic = artifactsManager;
327 public ApplicationDataTypeCache getApplicationDataTypeCache() {
328 return applicationDataTypeCache;
332 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
333 this.applicationDataTypeCache = applicationDataTypeCache;
337 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
338 this.interfaceTypeOperation = interfaceTypeOperation;
342 * the method returns a list of all the resources that are certified, the
343 * returned resources are only abstract or only none abstract according to
351 public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter,
353 User user = validateUserExists(userId);
354 Boolean isHighest = null;
355 switch (highestFilter) {
361 case NON_HIGHEST_ONLY:
367 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
368 .getAllCertifiedResources(getAbstract, isHighest);
370 if (getResponse.isRight()) {
371 throw new StorageException(getResponse.right()
375 return getResponse.left()
379 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
380 ResourceTypeEnum resourceTypeEnum, String userId) {
382 validateUserExists(userId);
384 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
385 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
387 janusGraphDao.commit();
389 if (dataModelResponse.isLeft()) {
390 Map<String, Boolean> result = new HashMap<>();
391 result.put("isValid", dataModelResponse.left()
393 log.debug("validation was successfully performed.");
394 return Either.left(result);
397 ResponseFormat responseFormat = componentsUtils
398 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
401 return Either.right(responseFormat);
404 public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user,
405 Map<String, byte[]> csarUIPayload, String payloadName) {
406 validateResourceBeforeCreate(resource, user, false);
407 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
408 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId());
409 if (StringUtils.isNotEmpty(csarUUID)) {
410 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
411 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
413 Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
414 return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left()
415 .map(r -> (Resource) r)
420 final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
421 return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left()
422 .map(r -> (Resource) r)
427 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
428 String payloadName, String resourceUniqueId) {
429 String csarUUID = payloadName;
430 String csarVersion = null;
431 Resource updatedResource = null;
432 if (payloadName == null) {
433 csarUUID = resource.getCsarUUID();
434 csarVersion = resource.getCsarVersion();
436 if (csarUUID != null && !csarUUID.isEmpty()) {
437 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
438 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
439 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
440 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
441 overrideImmutableMetadata(oldResource, resource);
443 validateResourceBeforeCreate(resource, user, false);
444 String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null;
445 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
447 // (on boarding flow): If the update includes same csarUUID and
448 // same csarVersion as already in the VF - no need to import the
449 // csar (do only metadata changes if there are).
450 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
451 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
453 updatedResource = updateResourceFromCsar(oldResource, resource, user,
454 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
457 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
458 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
460 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
461 throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
463 return updatedResource;
466 private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
467 // (on boarding flow): If the update includes a csarUUID: verify this
468 // csarUUID is not in use by another VF, If it is - use same error as
470 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
471 // select another or update the existing VF." %1 - csarUUID, %2 - VF
473 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
474 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
475 if (resourceLinkedToCsarRes.isRight()) {
476 if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
477 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
478 resource.getSystemName());
479 throw new StorageException(resourceLinkedToCsarRes.right()
482 } else if (!resourceLinkedToCsarRes.left()
485 .equals(oldResource.getUniqueId())
486 && !resourceLinkedToCsarRes.left()
489 .equals(oldResource.getName())) {
490 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
491 resourceLinkedToCsarRes.left()
494 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
495 throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left()
501 private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID,
502 String resourceUniqueId, User user) {
503 // (on boarding flow): If the update includes csarUUID which is
504 // different from the csarUUID of the VF - fail with
505 // error: "Error: Resource %1 cannot be updated using since it is linked
506 // to a different VSP" %1 - VF name
507 String oldCsarUUID = oldResource.getCsarUUID();
508 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
510 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
511 resourceUniqueId, csarUUID, oldCsarUUID);
512 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
513 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
514 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
515 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID,
520 private Resource getResourceByUniqueId(String resourceUniqueId) {
521 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade
522 .getToscaFullElement(resourceUniqueId);
523 if (oldResourceRes.isRight()) {
524 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
525 oldResourceRes.right()
527 throw new StorageException(oldResourceRes.right()
530 return oldResourceRes.left()
534 private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
535 resource.setName(oldResource.getName());
536 resource.setIcon(oldResource.getIcon());
537 resource.setTags(oldResource.getTags());
538 resource.setCategories(oldResource.getCategories());
539 resource.setDerivedFrom(oldResource.getDerivedFrom());
542 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user,
543 AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload,
545 Resource updatedResource = null;
546 validateLifecycleState(oldResource, user);
547 String lockedResourceId = oldResource.getUniqueId();
548 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
549 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
550 lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
552 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
554 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
555 nodeTypesInfo, csarInfo, oldResource);
556 if (findNodeTypesArtifactsToHandleRes.isRight()) {
557 log.debug("failed to find node types for update with artifacts during import csar {}. ",
558 csarInfo.getCsarUUID());
559 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right()
562 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
566 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts,
567 csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo,
568 nodeTypesArtifactsToHandle, null, false);
570 } catch (ComponentException | StorageException e) {
571 rollback(inTransaction, newResource, createdArtifacts, null);
575 janusGraphDao.commit();
576 log.debug("unlock resource {}", lockedResourceId);
577 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
579 return updatedResource;
583 private void validateLifecycleState(Resource oldResource, User user) {
584 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState()
585 && !oldResource.getLastUpdaterUserId()
586 .equals(user.getUserId())) {
588 "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
589 oldResource.getLastUpdaterUserId(), user.getUserId());
590 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
594 private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
595 List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
596 Map<String, NodeTypeInfo> nodeTypesInfo,
597 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
598 String nodeName, boolean isNested) {
599 boolean inTransaction = true;
600 boolean shouldLock = false;
601 Resource preparedResource = null;
602 ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
604 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName,
605 nodeTypesInfo, csarInfo, nodeName, oldResource);
606 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
607 if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
608 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
610 preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(),
611 inTransaction, shouldLock, isNested).left;
612 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
613 handleResourceGenericType(preparedResource);
614 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle,
615 createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
616 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
617 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
618 preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
619 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames);
620 } catch (ComponentException e) {
621 ResponseFormat responseFormat = e.getResponseFormat() == null
622 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
623 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
625 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
626 preparedResource == null ? oldResource : preparedResource, actionEnum);
628 } catch (StorageException e) {
629 ResponseFormat responseFormat = componentsUtils
630 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
631 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
633 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
634 preparedResource == null ? oldResource : preparedResource, actionEnum);
637 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
638 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
639 preparedResource.getSystemName());
640 if (validateUpdateVfGroupNamesRes.isRight()) {
642 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right()
645 // add groups to newResource
646 Map<String, GroupDefinition> groups;
648 if (!validateUpdateVfGroupNamesRes.left()
651 groups = validateUpdateVfGroupNamesRes.left()
654 groups = uploadComponentInstanceInfoMap.getGroups();
656 handleGroupsProperties(preparedResource, groups);
657 Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
659 preparedResource = updateGroupsOnResource(preparedResource, groups);
661 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
662 nodeTypesArtifactsToHandle);
664 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE,
665 createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts,
666 inTransaction, shouldLock);
667 if (updateArtifactsEither.isRight()) {
668 log.debug("failed to update artifacts {}", updateArtifactsEither.right()
670 throw new ByResponseFormatComponentException(updateArtifactsEither.right()
673 preparedResource = getResourceWithGroups(updateArtifactsEither.left()
677 updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
678 updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
680 final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
681 preparedResource = getResourceWithGroups(preparedResourceId);
683 updateVolumeGroup(preparedResource);
685 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
686 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
687 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
689 throw new ByResponseFormatComponentException(responseFormat);
691 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
693 return preparedResource;
696 protected void updateVolumeGroup(Resource preparedResource) {
697 List<GroupDefinition> groups = preparedResource.safeGetGroups();
698 for (GroupDefinition group : groups) {
699 Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
700 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
701 List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
702 if (!volumePropList.isEmpty()) {
703 PropertyDataDefinition volumeProp = volumePropList.get(0);
704 if (volumeProp != null) {
705 boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
707 if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
708 volumeProp.setValue(String.valueOf(isVolumeGroup));
709 volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
717 private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
718 if (oldResource == null || preparedResource == null) {
719 log.debug("Failed to update groups name : oldResource or preparedResource is null");
720 } else if (CollectionUtils.isNotEmpty(oldResource.getGroups())
721 && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
722 Map<String, String> oldGroups = oldResource.getGroups()
724 .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
726 List<GroupDefinition> updatedGroups = preparedResource.getGroups()
728 .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
729 .equals(oldGroups.get(group.getInvariantName())))
732 if (CollectionUtils.isNotEmpty(updatedGroups)) {
733 if (isTopologyChanged) {
734 updatedGroups.stream().filter(group -> !group.isVspOriginated())
735 .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
737 updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
739 groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
744 private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource,
745 boolean isTopologyChanged) {
746 if (oldResource == null || preparedResource == null) {
747 log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
749 if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
750 Map<String, String> oldInstances = oldResource.getComponentInstances()
752 .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
753 List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
755 .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
756 .equals(oldInstances.get(i.getInvariantName())))
758 if (CollectionUtils.isNotEmpty(updatedInstances)) {
759 if (isTopologyChanged) {
760 updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
761 .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
763 updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
768 componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
769 null, preparedResource.getUniqueId(), csarInfo.getModifier()
771 preparedResource.getComponentInstances(), false);
775 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
776 List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
777 Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
778 boolean inTransaction, boolean shouldLock) {
780 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
781 Resource resource = preparedResource;
783 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
784 .getNodeTypesArtifactsToHandle();
785 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
786 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
787 && !nodeTypesArtifactsToHandle.get(nodeName)
789 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
790 preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
791 csarInfo.getModifier(), inTransaction, true);
792 if (handleNodeTypeArtifactsRes.isRight()) {
793 return Either.right(handleNodeTypeArtifactsRes.right()
798 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
799 csarInfo, createdArtifacts,
800 new ArtifactOperationInfo(false, false, operation), shouldLock,
802 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
803 if (createdCsarArtifactsEither.isRight()) {
804 return createdCsarArtifactsEither;
807 resource = createdCsarArtifactsEither.left()
810 return Either.left(resource);
813 private Resource handleResourceGenericType(Resource resource) {
814 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
815 if (resource.shouldGenerateInputs()) {
816 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
818 return genericResource;
821 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
822 final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
824 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
825 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
826 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
829 final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
830 .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
831 final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
832 nodeTypesInfo, oldResource.getName(), csarInfo);
833 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
834 oldResource.getName(), csarInfo.getCsarUUID());
835 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
836 nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
837 } catch (Exception e) {
838 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
839 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
840 log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
842 return nodeTypesArtifactsToHandleRes;
845 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
846 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
847 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
848 ImmutablePair<String, String> vfcToscaNames) {
850 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
851 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
852 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
854 if (!isEmpty(extractedVfcsArtifacts)) {
855 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
856 if (extractedVfcsArtifacts.containsKey(namespace)) {
857 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
859 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
860 } else if (curNodeType != null) {
861 // delete all artifacts if have not received artifacts from
863 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
864 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
865 // delete all informational artifacts
866 artifactsToDelete.addAll(curNodeType.getArtifacts()
869 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
871 // delete all deployment artifacts
872 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
874 if (!artifactsToDelete.isEmpty()) {
875 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
878 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
879 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
883 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
884 String previousVfcToscaName, StorageOperationStatus status) {
885 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
886 log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
888 ResponseFormat responseFormat = componentsUtils
889 .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
890 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
891 AuditingActionEnum.CREATE_RESOURCE);
892 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
893 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
894 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
896 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
901 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
902 List<ArtifactDefinition> extractedArtifacts) {
905 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
906 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
907 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
908 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
909 artifactsToDelete, collectExistingArtifacts(curNodeType));
910 return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
911 } catch (Exception e) {
912 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
913 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
917 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
918 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
919 List<ArtifactDefinition> artifactsToDelete) {
920 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
921 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
922 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
923 if (!artifactsToUpload.isEmpty()) {
924 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
926 if (!artifactsToUpdate.isEmpty()) {
927 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
929 if (!artifactsToDelete.isEmpty()) {
930 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
933 return nodeTypeArtifactsToHandle;
936 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
937 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
938 List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
939 if (!existingArtifacts.isEmpty()) {
940 extractedArtifacts.stream()
941 .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
942 artifactsToDelete.addAll(existingArtifacts.values());
946 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
947 List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
948 ArtifactDefinition currNewArtifact) {
949 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
951 .filter(a -> a.getArtifactName()
952 .equals(currNewArtifact.getArtifactName()))
954 if (foundArtifact.isPresent()) {
955 if (foundArtifact.get()
957 .equals(currNewArtifact.getArtifactType())) {
958 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
959 existingArtifacts.remove(foundArtifact.get()
960 .getArtifactLabel());
961 artifactsToUpload.remove(currNewArtifact);
963 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
964 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
965 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
971 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
972 ArtifactDefinition foundArtifact) {
973 if (!foundArtifact.getArtifactChecksum()
974 .equals(currNewArtifact.getArtifactChecksum())) {
975 foundArtifact.setPayload(currNewArtifact.getPayloadData());
976 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
977 foundArtifact.setArtifactChecksum(
978 GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
979 artifactsToUpdate.add(foundArtifact);
983 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
984 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
985 if (curNodeType == null) {
986 return existingArtifacts;
988 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
989 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
991 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
992 existingArtifacts.putAll(curNodeType.getArtifacts()
995 .filter(e -> e.getValue()
996 .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
997 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
999 return existingArtifacts;
1003 * Changes resource life cycle state to checked out
1007 * @param inTransaction
1010 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
1011 Either<Resource, ResponseFormat> checkoutResourceRes;
1013 if (!resource.getComponentMetadataDefinition()
1014 .getMetadataDataDefinition()
1016 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
1018 "************* Going to change life cycle state of resource {} to not certified checked out. ",
1019 resource.getName());
1020 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
1021 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1022 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1023 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
1024 inTransaction, true);
1025 if (checkoutRes.isRight()) {
1026 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
1027 resource.getComponentType()
1029 resource.getUniqueId(), checkoutRes.right()
1032 checkoutResourceRes = Either.right(checkoutRes.right()
1035 checkoutResourceRes = Either.left((Resource) checkoutRes.left()
1039 checkoutResourceRes = Either.left(resource);
1041 } catch (Exception e) {
1042 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1043 checkoutResourceRes = Either.right(responseFormat);
1044 log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
1047 return checkoutResourceRes;
1051 * Handles Artifacts of NodeType
1053 * @param nodeTypeResource
1054 * @param nodeTypeArtifactsToHandle
1056 * @param inTransaction
1059 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
1060 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1061 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
1062 List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
1063 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1064 Either<Resource, ResponseFormat> changeStateResponse;
1066 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1067 if (changeStateResponse.isRight()) {
1068 return Either.right(changeStateResponse.right()
1071 nodeTypeResource = changeStateResponse.left()
1074 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1075 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1076 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1078 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1079 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1080 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1081 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
1082 nodeTypeResource.getName());
1083 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1084 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
1085 createdArtifacts, new ArtifactOperationInfo(false,
1086 ignoreLifecycleState, curOperation),
1087 false, inTransaction);
1088 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1089 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1091 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1094 if (handleNodeTypeArtifactsRes == null) {
1095 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1097 } catch (Exception e) {
1098 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1099 handleNodeTypeArtifactsRes = Either.right(responseFormat);
1100 log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1102 return handleNodeTypeArtifactsRes;
1105 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
1106 final String vfResourceName,
1107 final CsarInfo csarInfo) {
1108 final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
1110 final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
1111 if (!nodes.isEmpty()) {
1112 final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
1113 while (nodesNameEntry.hasNext()) {
1114 final Entry<String, Object> nodeType = nodesNameEntry.next();
1115 final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
1116 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
1117 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
1120 for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
1121 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
1122 vfResourceName, cvfc.getType()));
1124 return vfcToscaNames;
1127 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1128 Map<String, Object> nodes = new HashMap<>();
1129 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
1130 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
1132 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
1136 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
1137 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1138 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
1139 if (eitherNodeTypes.isLeft()) {
1140 nodes.putAll(eitherNodeTypes.left()
1145 public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
1147 log.trace("************* created successfully from YAML, resource TOSCA ");
1148 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
1149 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
1150 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
1151 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
1152 nodeTypesInfo, csarInfo, resource);
1153 if (findNodeTypesArtifactsToHandleRes.isRight()) {
1154 log.debug("failed to find node types for update with artifacts during import csar {}. ",
1155 csarInfo.getCsarUUID());
1156 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1157 StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
1158 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
1160 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
1161 csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
1164 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
1165 vfResource.getToscaResourceName());
1166 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
1170 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1171 log.trace("validating resource before create");
1172 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
1173 // validate user role
1174 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
1175 // VF / PNF "derivedFrom" should be null (or ignored)
1176 if (ModelConverter.isAtomicComponent(resource)) {
1177 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1179 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1183 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
1184 // nodeTypesArtifactsToCreate, true, false, null
1185 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1186 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1187 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1188 boolean shouldLock, boolean inTransaction, String nodeName) {
1190 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
1191 Resource createdResource;
1193 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
1194 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
1195 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1197 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
1198 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1199 StatusCode.STARTED,"");
1200 createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1201 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
1202 csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1203 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
1204 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1205 StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
1206 } catch (ComponentException e) {
1207 ResponseFormat responseFormat = e.getResponseFormat() == null
1208 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
1209 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1210 AuditingActionEnum.IMPORT_RESOURCE);
1212 } catch (StorageException e) {
1213 ResponseFormat responseFormat = componentsUtils
1214 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1215 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1216 AuditingActionEnum.IMPORT_RESOURCE);
1219 return createdResource;
1223 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
1224 Map<String, Object> mappedToscaTemplate, boolean needLock,
1225 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1226 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1227 CsarInfo csarInfo) {
1229 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1230 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1231 if (toscaVersion.isRight()) {
1232 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1234 Map<String, Object> mapToConvert = new HashMap<>();
1235 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
1237 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1238 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1239 nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1240 return csarInfo.getCreatedNodes();
1243 private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1244 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1246 .orValue(HashMap::new);
1249 private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1250 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1251 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1252 CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1253 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
1255 Resource vfcCreated = null;
1256 while (nodesNameValueIter.hasNext()) {
1257 Entry<String, Object> nodeType = nodesNameValueIter.next();
1258 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1259 || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1261 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1262 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1263 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1264 nodeTypesInfo, csarInfo, nodeType.getKey());
1265 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1266 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1267 && !csarInfo.getCreatedNodesToscaResourceNames()
1268 .containsKey(nodeType.getKey())) {
1269 log.trace("************* Going to create node {}", nodeType.getKey());
1270 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
1271 nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
1272 nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1273 log.debug("************* Finished to create node {}", nodeType.getKey());
1275 vfcCreated = resourceCreated.getLeft();
1276 csarInfo.getCreatedNodesToscaResourceNames()
1277 .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1279 if (vfcCreated != null) {
1280 csarInfo.getCreatedNodes()
1281 .put(nodeType.getKey(), vfcCreated);
1283 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1287 private Resource handleNestedVfc(Resource resource,
1288 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1289 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1292 String yamlName = nodesInfo.get(nodeName)
1293 .getTemplateFileName();
1294 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
1295 .getMappedToscaTemplate();
1297 log.debug("************* Going to create node types from yaml {}", yamlName);
1298 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
1299 createdArtifacts, Collections.emptyMap(), csarInfo);
1300 log.debug("************* Finished to create node types from yaml {}", yamlName);
1302 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1303 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1304 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
1305 nodeName, yamlName);
1310 private Resource handleComplexVfc(final Resource resource,
1311 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
1312 nodesArtifactsToHandle,
1313 final List<ArtifactDefinition>
1314 createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1315 final String nodeName, final String yamlName) {
1317 Resource oldComplexVfc = null;
1318 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1319 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1320 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1321 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1322 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1323 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1325 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1326 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1327 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1328 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1329 } else if (oldComplexVfcRes.isLeft()) {
1330 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1331 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1332 oldComplexVfcRes.left().value(),
1333 newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1334 if (eitherValidation.isLeft()) {
1335 oldComplexVfc = oldComplexVfcRes.left().value();
1338 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
1339 yamlName, oldComplexVfc, newComplexVfc);
1340 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1341 final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1342 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1343 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1344 final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
1345 lifecycleChangeInfo, true, false, true);
1346 csarInfo.getCreatedNodes().put(nodeName, result);
1347 csarInfo.removeNodeFromQueue();
1351 private Resource handleComplexVfc(
1352 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1353 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1354 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1356 Resource handleComplexVfcRes;
1357 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
1358 .getMappedToscaTemplate();
1359 String yamlContent = new String(csarInfo.getCsar()
1361 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
1363 .collect(toMap(Entry::getKey, e -> e.getValue()
1364 .getUnmarkedCopy()));
1365 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1366 if (oldComplexVfc == null) {
1367 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1368 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1370 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1371 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1372 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1374 return handleComplexVfcRes;
1377 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1378 Map<String, NodeTypeInfo> nodesInfo) {
1380 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1381 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1382 csarInfo.addNodeToQueue(nodeName);
1383 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
1387 private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
1389 final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
1390 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1392 if(findTypes.length > 1){
1393 final String resourceType = findTypes[0];
1394 return nameWithouNamespacePrefix.substring(resourceType.length());
1396 return nameWithouNamespacePrefix;
1399 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
1400 final Entry<String, Object> nodeNameValue,
1402 final Map<String, Object> mapToConvert,
1403 final Resource resourceVf,
1404 final boolean needLock,
1405 final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1406 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1407 final boolean forceCertificationAllowed,
1408 final CsarInfo csarInfo,
1409 final boolean isNested) {
1411 final UploadResourceInfo resourceMetaData = fillResourceMetadata(
1412 yamlName, resourceVf, nodeNameValue.getKey(), user);
1414 final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1415 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1416 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1417 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1418 nodeNameValue.getKey(), isNested);
1421 private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
1422 final Map<String, Object> mapToConvert,
1423 final String nodeResourceType,
1424 final CsarInfo csarInfo) {
1425 // We need to create a Yaml from each node_types in order to create
1426 // resource from each node type using import normative flow.
1427 final DumperOptions options = new DumperOptions();
1428 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1429 final Yaml yaml = new Yaml(options);
1431 final Map<String, Object> node = new HashMap<>();
1432 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1433 .getLeft(), nodeNameValue.getValue());
1434 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1436 return yaml.dumpAsMap(mapToConvert);
1439 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1440 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1444 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
1445 UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1446 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1447 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1448 String nodeName, boolean isNested) {
1450 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1451 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1452 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1454 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1455 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1456 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1460 * Validates if a given node type name has a valid prefix.
1462 * @param nodeName node name from definition file
1463 * @param definedResourceNamespaceList is a list of all node type name prefix allowed
1464 * @return a valid node type name prefix if it`s found
1466 public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
1467 final List<String> definedResourceNamespaceList) {
1468 for (final String validNamespace : definedResourceNamespaceList) {
1469 if (nodeName.startsWith(validNamespace)) {
1470 return Optional.of(validNamespace);
1473 return Optional.empty();
1476 private List<String> getDefinedNodeTypeNamespaceList() {
1477 return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
1480 private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
1481 final String nodeName, final User user) {
1483 final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1485 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
1486 log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
1488 if (!nodeName.startsWith(nodeTypeNamePrefix)) {
1489 log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
1490 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1491 resourceMetaData.getName(), nodeName);
1494 final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
1495 final String namePrefix = nodeName.replace(actualName, "");
1496 String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
1497 log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
1498 resourceType, nodeName, actualName, nodeTypeNamePrefix);
1500 // if we import from csar, the node_type name can be
1501 // org.openecomp.resource.abstract.node_name - in this case we always
1503 if (resourceType.equals(Constants.ABSTRACT)) {
1504 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1507 if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
1508 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1512 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1513 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
1514 resourceType.toUpperCase(), ResourceTypeEnum.values());
1515 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1516 resourceMetaData.getName(), nodeName);
1520 resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
1522 // Setting type from name
1523 final String type = resourceType.toUpperCase();
1524 resourceMetaData.setResourceType(type);
1526 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1527 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1528 resourceMetaData.setContactId(user.getUserId());
1529 resourceMetaData.setVendorName(resourceVf.getVendorName());
1530 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1533 final List<String> tags = new ArrayList<>();
1534 tags.add(resourceMetaData.getName());
1535 resourceMetaData.setTags(tags);
1538 final CategoryDefinition category = new CategoryDefinition();
1539 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1540 final SubCategoryDefinition subCategory = new SubCategoryDefinition();
1541 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1542 category.addSubCategory(subCategory);
1543 final List<CategoryDefinition> categories = new ArrayList<>();
1544 categories.add(category);
1545 resourceMetaData.setCategories(categories);
1547 return resourceMetaData;
1550 private Resource buildComplexVfcMetadata(final Resource resourceVf,
1551 final CsarInfo csarInfo,
1552 final String nodeName,
1553 final Map<String, NodeTypeInfo> nodesInfo) {
1554 final Resource cvfc = new Resource();
1555 final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1556 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1557 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1558 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1559 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1560 cvfc.setAbstract(true);
1561 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1562 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1563 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1564 cvfc.setContactId(csarInfo.getModifier()
1566 cvfc.setCreatorUserId(csarInfo.getModifier()
1568 cvfc.setVendorName(resourceVf.getVendorName());
1569 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1570 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1571 cvfc.setToscaResourceName(buildNestedToscaResourceName(
1572 ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1573 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1575 final List<String> tags = new ArrayList<>();
1576 tags.add(cvfc.getName());
1579 final CategoryDefinition category = new CategoryDefinition();
1580 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1581 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1582 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1583 category.addSubCategory(subCategory);
1584 final List<CategoryDefinition> categories = new ArrayList<>();
1585 categories.add(category);
1586 cvfc.setCategories(categories);
1588 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1589 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1590 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1595 private String buildCvfcName(final String resourceVfName, final String nodeName) {
1597 String nameWithouNamespacePrefix =
1598 nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1599 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1600 String resourceType = findTypes[0];
1601 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1602 return addCvfcSuffixToResourceName(resourceName);
1605 private Resource createResourceAndRIsFromYaml(final String yamlName,
1607 final ParsedToscaYamlInfo parsedToscaYamlInfo,
1608 final AuditingActionEnum actionEnum,
1609 final boolean isNormative,
1610 final List<ArtifactDefinition> createdArtifacts,
1611 final String topologyTemplateYaml,
1612 final Map<String, NodeTypeInfo> nodeTypesInfo,
1613 final CsarInfo csarInfo,
1614 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1615 final boolean shouldLock,
1616 final boolean inTransaction,
1617 final String nodeName) {
1619 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1622 final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1624 if (lockResult.isRight()) {
1625 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1626 throw new ByResponseFormatComponentException(lockResult.right().value());
1628 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1631 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1632 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
1633 final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1634 resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
1635 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1636 log.trace("************* Going to add inputs from yaml {}", yamlName);
1637 if (resource.shouldGenerateInputs())
1638 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1640 final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1641 resource = createInputsOnResource(resource, inputs);
1642 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1643 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
1644 resource.getComponentMetadataForSupportLog(),
1645 StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
1646 if (resource.getResourceType() == ResourceTypeEnum.PNF) {
1647 log.trace("************* Adding generic properties to PNF");
1648 resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
1649 genericResource.getProperties());
1650 log.trace("************* Adding software information to PNF");
1651 softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
1652 log.trace("************* Removing non-mano software information file from PNF");
1653 if (csarInfo.getSoftwareInformationPath().isPresent() &&
1654 !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
1655 log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
1656 "catalog-be", "Could not remove the software information file.");
1660 final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1662 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1663 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName);
1664 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1665 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
1667 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1668 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
1669 resource.getComponentMetadataForSupportLog(),
1670 StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName);
1671 // validate update vf module group names
1672 final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1673 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1674 if (validateUpdateVfGroupNamesRes.isRight()) {
1675 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1676 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1678 // add groups to resource
1679 final Map<String, GroupDefinition> groups;
1680 log.trace("************* Going to add groups from yaml {}", yamlName);
1681 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
1682 StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
1683 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1684 groups = validateUpdateVfGroupNamesRes.left().value();
1686 groups = parsedToscaYamlInfo.getGroups();
1689 final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
1690 if (createGroupsOnResource.isRight()) {
1691 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1692 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1693 resource.getComponentMetadataForSupportLog(),
1694 StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
1695 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1697 resource = createGroupsOnResource.left().value();
1698 log.trace("************* Finished to add groups from yaml {}", yamlName);
1699 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1700 resource.getComponentMetadataForSupportLog(),
1701 StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
1702 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1703 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1704 resource.getComponentMetadataForSupportLog(),
1705 StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
1707 log.trace("************* Starting to add policies from yaml {}", yamlName);
1708 Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
1709 if (MapUtils.isNotEmpty(policies)) {
1710 resource = createPoliciesOnResource(resource, policies);
1712 log.trace("************* Finished to add policies from yaml {}", yamlName);
1714 final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
1715 new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
1717 final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
1718 ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
1719 nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1720 if (createArtifactsEither.isRight()) {
1721 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1722 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1723 resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
1724 createArtifactsEither.right().value());
1725 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1727 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1728 resource.getComponentMetadataForSupportLog(),
1729 StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
1730 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1731 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1732 ASDCKpiApi.countCreatedResourcesKPI();
1735 } catch (final ComponentException | StorageException e) {
1736 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1738 } catch (final ToscaOperationException e) {
1739 log.error("An error has occurred during resource and resource instance creation", e);
1740 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1741 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
1742 "catalog-be", e.getMessage());
1743 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1744 } catch (final BusinessLogicException e) {
1745 log.error("An error has occurred during resource and resource instance creation", e);
1746 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1747 throw new ByResponseFormatComponentException(e.getResponseFormat());
1749 if (!inTransaction) {
1750 janusGraphDao.commit();
1753 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1754 NodeTypeEnum.Resource);
1759 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1760 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1761 if (!inTransaction) {
1762 janusGraphDao.rollback();
1764 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1765 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1766 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
1767 resource.getName());
1771 private Resource getResourceWithGroups(String resourceId) {
1773 ComponentParametersView filter = new ComponentParametersView();
1774 filter.setIgnoreGroups(false);
1775 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
1777 if (updatedResource.isRight()) {
1778 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
1779 .value()), resourceId);
1781 return updatedResource.left()
1785 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1786 Map<String, GroupDefinition> groups) {
1787 if (groups != null && !groups.isEmpty()) {
1788 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1789 handleGroupsProperties(resource, groups);
1790 fillGroupsFinalFields(groupsAsList);
1791 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1792 groupsAsList, true);
1793 if (createGroups.isRight()) {
1794 return Either.right(createGroups.right()
1798 return Either.left(resource);
1801 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1802 List<InputDefinition> inputs = resource.getInputs();
1803 if (MapUtils.isNotEmpty(groups)) {
1806 .filter(g -> isNotEmpty(g.getProperties()))
1807 .flatMap(g -> g.getProperties()
1809 .forEach(p -> handleGetInputs(p, inputs));
1813 private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
1814 policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
1818 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1819 if (isNotEmpty(property.getGetInputValues())) {
1820 if (inputs == null || inputs.isEmpty()) {
1821 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1822 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1824 .map(GetInputValueDataDefinition::getInputName)
1828 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
1830 while (getInputValuesIter.hasNext()) {
1831 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1832 Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
1833 if (inputEither.isRight()) {
1834 throw inputEither.right().value();
1836 InputDefinition input = inputEither.left().value();
1837 getInput.setInputId(input.getUniqueId());
1838 if (getInput.getGetInputIndex() != null) {
1839 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1840 Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
1842 if (newInputEither.isRight()) {
1843 throw newInputEither.right().value();
1845 InputDefinition newInput = newInputEither.left().value();
1846 getInputIndex.setInputId(newInput.getUniqueId());
1848 getInputValuesIter.add(getInputIndex);
1855 static <T> Either<T, RuntimeException> rollbackWithEither(
1856 final JanusGraphDao janusGraphDao,
1857 final ActionStatus actionStatus,
1858 final String... params) {
1859 if (janusGraphDao != null)
1860 janusGraphDao.rollback();
1861 return Either.right(new ByActionStatusComponentException(actionStatus, params));
1864 <T> Either<T, RuntimeException> rollbackWithEither(
1865 final ActionStatus actionStatus,
1866 final String... params) {
1867 return rollbackWithEither(janusGraphDao, actionStatus, params);
1870 private Either<InputDefinition, RuntimeException> findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1872 final String inputName = getInput != null ? getInput.getInputName() : "";
1874 if(inputs == null || inputs.isEmpty()) {
1875 log.debug("#findInputByName - Inputs list is empty");
1876 return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
1878 Optional<InputDefinition> inputOpt = inputs.stream()
1879 .filter(p -> p.getName().equals(inputName))
1881 if (!inputOpt.isPresent()) {
1882 log.debug("#findInputByName - Failed to find the input {} ", inputName);
1883 return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
1885 return Either.left(inputOpt.get());
1890 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1891 groupsAsList.forEach(groupDefinition -> {
1892 groupDefinition.setInvariantName(groupDefinition.getName());
1893 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1897 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1898 if (isEmpty(groups)) {
1901 return updateOrCreateGroups(resource, groups);
1904 private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1905 List<GroupDefinition> groupsFromResource = resource.getGroups();
1906 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1907 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1908 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1909 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1910 if (isNotEmpty(groupsFromResource)) {
1911 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1912 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1914 groupsToCreate.addAll(groupsAsList);
1916 if (isNotEmpty(groupsToCreate)) {
1917 fillGroupsFinalFields(groupsToCreate);
1918 if (isNotEmpty(groupsFromResource)) {
1919 groupBusinessLogic.addGroups(resource, groupsToCreate, true)
1921 .on(this::throwComponentException);
1923 groupBusinessLogic.createGroups(resource, groupsToCreate, true)
1925 .on(this::throwComponentException);
1928 if (isNotEmpty(groupsToDelete)) {
1929 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1931 .on(this::throwComponentException);
1933 if (isNotEmpty(groupsToUpdate)) {
1934 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1936 .on(this::throwComponentException);
1942 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1943 List<GroupDefinition> groupsToDelete) {
1944 for (GroupDefinition group : groupsFromResource) {
1945 Optional<GroupDefinition> op = groupsAsList.stream()
1946 .filter(p -> p.getInvariantName()
1947 .equalsIgnoreCase(group.getInvariantName()))
1949 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
1951 groupsToDelete.add(group);
1956 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1957 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1958 for (GroupDefinition group : groupsAsList) {
1959 Optional<GroupDefinition> op = groupsFromResource.stream()
1960 .filter(p -> p.getInvariantName()
1961 .equalsIgnoreCase(group.getInvariantName()))
1963 if (op.isPresent()) {
1964 GroupDefinition groupToUpdate = op.get();
1965 groupToUpdate.setMembers(group.getMembers());
1966 groupToUpdate.setCapabilities(group.getCapabilities());
1967 groupToUpdate.setProperties(group.getProperties());
1968 groupsToUpdate.add(groupToUpdate);
1970 groupsToCreate.add(group);
1975 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1976 List<InputDefinition> resourceProperties = resource.getInputs();
1977 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1979 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1981 if (createInputs.isRight()) {
1982 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
1983 StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
1985 throw new ByResponseFormatComponentException(createInputs.right()
1988 resource.setInputs(createInputs.left().value());
1993 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
1994 Resource component) {
1996 List<GroupDefinition> result = new ArrayList<>();
1997 List<ComponentInstance> componentInstances = component.getComponentInstances();
1999 if (groups != null) {
2000 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
2001 if (validateCyclicGroupsDependencies.isRight()) {
2002 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
2004 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
2005 String groupName = entry.getKey();
2006 GroupDefinition groupDefinition = entry.getValue();
2007 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2008 updatedGroupDefinition.setMembers(null);
2009 Map<String, String> members = groupDefinition.getMembers();
2010 if (members != null) {
2011 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
2014 result.add(updatedGroupDefinition);
2020 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
2021 Resource component, List<ComponentInstance> componentInstances, String groupName,
2022 Map<String, String> members) {
2023 Set<String> compInstancesNames = members.keySet();
2025 if (CollectionUtils.isEmpty(componentInstances)) {
2026 String membersAstString = compInstancesNames.stream()
2027 .collect(joining(","));
2029 "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
2030 membersAstString, groupName, component.getNormalizedName());
2031 throw new ByActionStatusComponentException(
2032 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2033 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2035 // Find all component instances with the member names
2036 Map<String, String> memberNames = componentInstances.stream()
2037 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2038 memberNames.putAll(groups.keySet()
2040 .collect(toMap(g -> g, g -> "")));
2041 Map<String, String> relevantInstances = memberNames.entrySet()
2043 .filter(n -> compInstancesNames.contains(n.getKey()))
2044 .collect(toMap(Entry::getKey, Entry::getValue));
2046 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2048 List<String> foundMembers = new ArrayList<>();
2049 if (relevantInstances != null) {
2050 foundMembers = relevantInstances.keySet()
2054 compInstancesNames.removeAll(foundMembers);
2055 String membersAstString = compInstancesNames.stream()
2056 .collect(joining(","));
2057 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
2058 component.getNormalizedName());
2059 throw new ByActionStatusComponentException(
2060 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2061 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2063 updatedGroupDefinition.setMembers(relevantInstances);
2067 * This Method validates that there is no cyclic group dependencies. meaning
2068 * group A as member in group B which is member in group A
2073 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
2075 Either<Boolean, ResponseFormat> result = Either.left(true);
2077 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
2079 while (allGroupsItr.hasNext() && result.isLeft()) {
2080 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
2081 // Fetches a group member A
2082 String groupAName = groupAEntry.getKey();
2083 // Finds all group members in group A
2084 Set<String> allGroupAMembersNames = new HashSet<>();
2085 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
2086 // If A is a group member of itself found cyclic dependency
2087 if (allGroupAMembersNames.contains(groupAName)) {
2088 ResponseFormat responseFormat = componentsUtils
2089 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
2090 result = Either.right(responseFormat);
2093 } catch (Exception e) {
2094 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2095 result = Either.right(responseFormat);
2096 log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
2102 * This Method fills recursively the set groupMembers with all the members
2103 * of the given group which are also of type group.
2107 * @param allGroupMembers
2110 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
2111 Set<String> allGroupMembers) {
2113 // Found Cyclic dependency
2114 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
2117 GroupDefinition groupDefinition = allGroups.get(groupName);
2118 // All Members Of Current Group Resource Instances & Other Groups
2119 Set<String> currGroupMembers = groupDefinition.getMembers()
2121 // Filtered Members Of Current Group containing only members which
2123 List<String> currGroupFilteredMembers = currGroupMembers.stream()
2125 // Keep Only Elements of type group and not Resource Instances
2126 filter(allGroups::containsKey)
2128 // Add Filtered Elements to main Set
2129 peek(allGroupMembers::add)
2134 // Recursively call the method for all the filtered group members
2135 for (String innerGroupName : currGroupFilteredMembers) {
2136 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
2141 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
2142 Set<String> allGroupMembers) {
2144 boolean stop = false;
2145 // In Case Not Group Stop
2146 if (!allGroups.containsKey(groupName)) {
2149 // In Case Group Has no members stop
2151 GroupDefinition groupDefinition = allGroups.get(groupName);
2152 stop = isEmpty(groupDefinition.getMembers());
2155 // In Case all group members already contained stop
2157 final Set<String> allMembers = allGroups.get(groupName)
2160 Set<String> membersOfTypeGroup = allMembers.stream()
2162 // Filter In Only Group members
2163 filter(allGroups::containsKey)
2167 stop = allGroupMembers.containsAll(membersOfTypeGroup);
2172 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
2173 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
2174 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2176 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2179 log.debug("************* Going to create all nodes {}", yamlName);
2180 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
2181 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
2182 log.debug("************* Finished to create all nodes {}", yamlName);
2183 log.debug("************* Going to create all resource instances {}", yamlName);
2184 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
2185 resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
2186 csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
2187 log.debug("************* Finished to create all resource instances {}", yamlName);
2188 log.debug("************* Going to create all relations {}", yamlName);
2189 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
2190 log.debug("************* Finished to create all relations {}", yamlName);
2191 log.debug("************* Going to create positions {}", yamlName);
2192 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
2194 log.debug("************* Finished to set positions {}", yamlName);
2198 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
2199 List<ArtifactDefinition> artifactsToAdd) {
2200 List<String> vfcArtifactNames = vfcArtifacts.stream()
2201 .map(ArtifactDataDefinition::getArtifactName)
2203 artifactsToAdd.stream()
2205 if (!vfcArtifactNames.contains(a.getArtifactName())) {
2206 vfcArtifacts.add(a);
2208 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
2214 @SuppressWarnings("unchecked")
2215 private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
2216 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2217 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2218 CsarInfo csarInfo, String nodeName) {
2220 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2221 if (nodeTypeEntry.getValue()
2224 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
2225 csarInfo, nodeTypeEntry.getKey());
2226 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2229 Map<String, Object> mappedToscaTemplate = null;
2230 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
2231 mappedToscaTemplate = nodeTypesInfo.get(nodeName)
2232 .getMappedToscaTemplate();
2234 if (isEmpty(mappedToscaTemplate)) {
2235 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2237 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
2238 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2239 } catch (ComponentException e) {
2240 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
2241 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
2242 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2243 AuditingActionEnum.IMPORT_RESOURCE);
2245 } catch (StorageException e) {
2246 ResponseFormat responseFormat = componentsUtils
2247 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2248 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2249 AuditingActionEnum.IMPORT_RESOURCE);
2254 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
2255 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
2256 boolean inTransaction) {
2258 if (csarInfo.getCsar() != null) {
2259 String vendorLicenseModelId = null;
2260 String vfLicenseModelId = null;
2262 if (artifactOperation.isUpdate()) {
2263 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
2264 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
2265 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
2266 if (artifactEntry.getValue()
2268 .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
2269 vendorLicenseModelId = artifactEntry.getValue()
2272 if (artifactEntry.getValue()
2274 .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
2275 vfLicenseModelId = artifactEntry.getValue()
2282 // Specific Behavior for license artifacts
2283 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2284 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
2285 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
2286 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
2287 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
2288 shouldLock, inTransaction);
2289 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2290 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
2291 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
2292 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
2293 artifactOperation, null, true, shouldLock, inTransaction);
2295 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
2296 createdArtifacts, shouldLock, inTransaction, artifactOperation);
2297 if (eitherCreateResult.isRight()) {
2298 return Either.right(eitherCreateResult.right()
2302 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
2303 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
2305 if (artifacsMetaCsarStatus.isLeft()) {
2306 String artifactsFileName = artifacsMetaCsarStatus.left()
2309 String artifactsContents = artifacsMetaCsarStatus.left()
2312 Either<Resource, ResponseFormat> createArtifactsFromCsar;
2313 if (artifactOperation.isCreateOrLink()) {
2314 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
2315 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
2317 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
2318 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
2320 if ((result.left().value() instanceof Resource) && result.isLeft()) {
2321 Resource service1 = (Resource) result.left().value();
2322 createArtifactsFromCsar = Either.left(service1);
2324 createArtifactsFromCsar = Either.right(result.right().value());
2328 if (createArtifactsFromCsar.isRight()) {
2329 log.debug("Couldn't create artifacts from artifacts.meta");
2330 return Either.right(createArtifactsFromCsar.right()
2334 return Either.left(createArtifactsFromCsar.left()
2338 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
2343 return Either.left(resource);
2346 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
2347 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
2348 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
2349 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
2350 boolean shouldLock, boolean inTransaction) {
2351 byte[] artifactFileBytes = null;
2353 if (csarInfo.getCsar()
2354 .containsKey(artifactPath)) {
2355 artifactFileBytes = csarInfo.getCsar()
2358 Either<Boolean, ResponseFormat> result = Either.left(true);
2359 if (operation.isUpdate() || operation.isDelete()) {
2360 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
2361 Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
2362 .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
2363 resource, shouldLock,
2365 if (handleDelete.isRight()) {
2366 result = Either.right(handleDelete.right()
2369 ArtifactDefinition value = handleDelete.left().value();
2370 String updatedArtifactId = value.getUniqueId();
2371 if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2372 resource.getDeploymentArtifacts().remove(updatedArtifactId);
2374 resource.getArtifacts().remove(updatedArtifactId);
2380 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2381 operation = new ArtifactOperationInfo(false, false,
2382 ArtifactOperationEnum.CREATE);
2386 if (artifactFileBytes != null) {
2387 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
2388 artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
2389 artifactDescription, artifactFileBytes, null, isFromCsar);
2390 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
2391 .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
2393 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2394 if (eitherNonMetaArtifacts.isRight()) {
2395 BeEcompErrorManager.getInstance()
2396 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2397 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2398 ErrorSeverity.WARNING);
2399 return Either.right(eitherNonMetaArtifacts.right()
2402 ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
2403 createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
2409 private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
2410 if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
2411 resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
2413 resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
2417 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2418 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2421 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2422 List<ArtifactDefinition> createdArtifacts,
2423 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2424 if (operation.isCreateOrLink() && createdArtifacts != null
2425 && eitherNonMetaArtifacts.isLeft()) {
2426 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
2428 if (eitherResult.isLeft()) {
2429 createdArtifacts.add(eitherResult.left()
2435 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2436 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2437 ArtifactOperationInfo artifactOperation) {
2439 Either<Resource, ResponseFormat> resStatus = null;
2440 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2443 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
2444 collectedWarningMessages);
2445 if (artifactPathAndNameList.isRight()) {
2446 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2447 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
2450 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2452 if (artifactOperation.isCreateOrLink()) {
2453 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2454 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
2457 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2458 resource, artifactPathAndNameList.left()
2460 csarInfo.getModifier());
2462 if (findVfCsarArtifactsToHandleRes.isRight()) {
2463 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
2466 if (resStatus == null) {
2467 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
2471 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2472 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
2473 resStatus, vfCsarArtifactsToHandle);
2475 if (resStatus == null) {
2476 resStatus = Either.left(resource);
2478 } catch (Exception e) {
2479 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2480 log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2482 CsarUtils.handleWarningMessages(collectedWarningMessages);
2487 private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
2488 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2489 Either<Resource, ResponseFormat> resStatus,
2490 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2491 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2494 Optional<ResponseFormat> optionalCreateInDBError =
2495 // Stream of artifacts to be created
2496 currArtifactOperationPair.getValue()
2498 // create each artifact
2499 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2500 e.getArtifactName(), e.getArtifactType(),
2501 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2502 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2503 new ArtifactOperationInfo(false, false,
2504 currArtifactOperationPair.getKey()),
2505 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2506 // filter in only error
2507 .filter(Either::isRight)
2509 // Convert the error from either to
2514 // Check if an error occurred
2516 // Error found on artifact Creation
2517 if (optionalCreateInDBError.isPresent()) {
2518 resStatus = Either.right(optionalCreateInDBError.get());
2525 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
2526 Map<String, Set<List<String>>> collectedWarningMessages) {
2527 List<NonMetaArtifactInfo> artifactPathAndNameList =
2528 // Stream of file paths contained in csar
2532 // Filter in only VF artifact path location
2533 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
2534 .matcher(e.getKey())
2536 // Validate and add warnings
2537 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2538 // Filter in Non Warnings
2539 .filter(Either::isLeft)
2540 // Convert from Either to NonMetaArtifactInfo
2545 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2546 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2547 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
2549 return Either.right(nonMetaArtifactInfo.getArtifactName());
2552 return Either.left(artifactPathAndNameList);
2555 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2556 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2558 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2559 // collect all Deployment and Informational artifacts of VF
2560 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
2562 existingArtifacts.addAll(resource.getDeploymentArtifacts()
2565 if (resource.getArtifacts() != null && !resource.getArtifacts()
2567 existingArtifacts.addAll(resource.getArtifacts()
2570 existingArtifacts = existingArtifacts.stream()
2571 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2572 // was created from HEAT.meta
2573 .filter(this::isNonMetaArtifact)
2576 List<String> artifactsToIgnore = new ArrayList<>();
2577 // collect IDs of Artifacts of VF which belongs to any group
2578 if (resource.getGroups() != null) {
2579 resource.getGroups()
2582 if (g.getArtifacts() != null && !g.getArtifacts()
2584 artifactsToIgnore.addAll(g.getArtifacts());
2588 existingArtifacts = existingArtifacts.stream()
2589 // filter artifacts which belongs to any group
2590 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
2592 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2595 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2596 boolean result = true;
2597 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2603 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2604 boolean result = true;
2605 if (artifact.getArtifactType() == null
2606 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2607 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2613 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
2614 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
2615 log.debug("#createResourceInstancesRelations - Going to create relations ");
2616 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations");
2617 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2618 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
2619 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
2621 "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
2622 resource.getUniqueId(), yamlName);
2623 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
2624 BeEcompErrorManager.getInstance()
2625 .logInternalDataError("createResourceInstancesRelations",
2626 "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2627 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2629 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2630 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2631 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2632 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2633 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2634 Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
2635 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2636 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2638 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2639 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2640 if (allDataTypes.isRight()) {
2641 JanusGraphOperationStatus status = allDataTypes.right()
2643 BeEcompErrorManager.getInstance()
2644 .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2645 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2646 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2647 StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
2648 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2649 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
2652 Resource finalResource = resource;
2653 uploadResInstancesMap.values()
2654 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2655 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
2656 instAttributes, existingNodeTypesByResourceNames, instInputs, i));
2657 resource.getComponentInstances()
2659 .filter(i -> !i.isCreatedFromCsar())
2660 .forEach(i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements,
2661 instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
2663 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2664 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2665 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2666 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2667 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2668 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2669 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2670 associateResourceInstances(yamlName, resource, relations);
2671 handleSubstitutionMappings(resource, uploadResInstancesMap);
2672 log.debug("************* in create relations, getResource start");
2673 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations");
2674 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2675 .getToscaFullElement(resource.getUniqueId());
2676 log.debug("************* in create relations, getResource end");
2677 if (eitherGetResource.isRight()) {
2678 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2679 StatusCode.ERROR,"ERROR while create relations");
2680 throw new ByResponseFormatComponentException(componentsUtils
2681 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
2682 .value()), resource));
2684 return eitherGetResource.left()
2688 private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
2689 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2690 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2691 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2692 Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String,
2693 List<ComponentInstanceProperty>> instProperties, Map<String,
2694 List<ComponentInstanceInput>> instInputs,
2695 Map<String, List<AttributeDefinition>> instAttributes) {
2696 Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
2697 if (foundInstance.isPresent()) {
2698 if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) {
2699 instCapabilities.put(instance, foundInstance.get().getCapabilities());
2701 if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) {
2702 instRequirements.put(instance, foundInstance.get().getRequirements());
2704 if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) {
2705 instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
2707 if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
2708 instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
2710 if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
2712 .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
2713 instProperties.put(instance.getUniqueId(),
2714 oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
2716 if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
2718 .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
2719 instInputs.put(instance.getUniqueId(),
2720 oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
2722 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
2723 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
2724 instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new).collect(toList()));
2729 private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
2730 if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
2731 return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
2733 return Optional.empty();
2736 private void associateResourceInstances(String yamlName, Resource resource,
2737 List<RequirementCapabilityRelDef> relations) {
2738 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2740 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2741 StorageOperationStatus status = relationsEither.right().value();
2742 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2744 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
2746 setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
2750 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2751 Map<String, List<AttributeDefinition>> instAttributes) {
2752 StorageOperationStatus addArtToInst;
2753 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2755 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2756 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2758 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst),
2763 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2764 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2765 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2766 StorageOperationStatus addArtToInst;
2767 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2769 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2770 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2772 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2776 private void associateArtifactsToInstances(String yamlName, Resource resource,
2777 Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2778 StorageOperationStatus addArtToInst;
2780 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2781 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2782 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2783 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2787 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2788 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2789 StorageOperationStatus addArtToInst = toscaOperationFacade
2790 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2791 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2792 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2793 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2797 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2798 Map<String, List<ComponentInstanceInput>> instInputs) {
2799 if (MapUtils.isNotEmpty(instInputs)) {
2800 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2801 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2802 if (addInputToInst.isRight()) {
2804 StorageOperationStatus addInputToInstError = addInputToInst.right().value();
2805 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2806 addInputToInstError);
2807 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
2809 setComponentInstanceInputsOnComponent(resource, instInputs);
2813 private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2814 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
2815 if (componentInstancesInputs == null)
2816 componentInstancesInputs = new HashMap<>();
2817 componentInstancesInputs.putAll(instInputs);
2818 resource.setComponentInstancesInputs(componentInstancesInputs);
2821 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2822 Map<String, List<ComponentInstanceProperty>> instProperties) {
2823 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2824 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2825 if (addPropToInst.isRight()) {
2826 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2827 StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
2828 StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
2829 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2830 storageOperationStatus);
2831 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
2833 setComponentInstancePropertiesOnComponent(resource, instProperties);
2836 private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2837 Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
2838 if (componentInstanceProps == null )
2839 componentInstanceProps = new HashMap<>();
2840 componentInstanceProps.putAll(instProperties);
2841 resource.setComponentInstancesProperties(componentInstanceProps);
2844 private void handleSubstitutionMappings(Resource resource,
2845 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2846 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2847 Either<Resource, StorageOperationStatus> getResourceRes =
2848 updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
2849 if (getResourceRes.isRight()) {
2850 ResponseFormat responseFormat = componentsUtils
2851 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
2852 .value()), resource);
2853 throw new ByResponseFormatComponentException(responseFormat);
2858 private void addRelationsToRI(String yamlName, Resource resource,
2859 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2860 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2861 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2862 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2863 ComponentInstance currentCompInstance = null;
2864 for (ComponentInstance compInstance : componentInstancesList) {
2866 if (compInstance.getName()
2867 .equals(uploadComponentInstanceInfo.getName())) {
2868 currentCompInstance = compInstance;
2873 if (currentCompInstance == null) {
2874 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2875 resource.getUniqueId());
2876 BeEcompErrorManager.getInstance()
2877 .logInternalDataError(
2878 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2879 resource.getUniqueId(), ErrorSeverity.ERROR);
2880 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2883 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2884 if (addRelationToRiRes.getStatus() != 200) {
2885 throw new ByResponseFormatComponentException(addRelationToRiRes);
2891 private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
2892 if (resource.getComponentInstancesRelations() != null) {
2893 resource.getComponentInstancesRelations().addAll(relations);
2895 resource.setComponentInstancesRelations(relations);
2899 private void processComponentInstance(String yamlName, Resource resource,
2900 List<ComponentInstance> componentInstancesList,
2901 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2902 Map<String, List<ComponentInstanceProperty>> instProperties,
2903 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2904 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2905 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2906 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
2907 Map<String, List<AttributeDefinition>> instAttributes,
2908 Map<String, Resource> originCompMap,
2909 Map<String, List<ComponentInstanceInput>> instInputs,
2910 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2911 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2912 .filter(i -> i.getName()
2913 .equals(uploadComponentInstanceInfo.getName()))
2915 if (!currentCompInstanceOpt.isPresent()) {
2916 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2917 resource.getUniqueId());
2918 BeEcompErrorManager.getInstance()
2919 .logInternalDataError(
2920 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2921 resource.getUniqueId(), ErrorSeverity.ERROR);
2922 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2924 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2925 String resourceInstanceId = currentCompInstance.getUniqueId();
2926 Resource originResource = getOriginResource(originCompMap, currentCompInstance);
2927 if (isNotEmpty(originResource.getRequirements())) {
2928 instRequirements.put(currentCompInstance, originResource.getRequirements());
2930 if (isNotEmpty(originResource.getCapabilities())) {
2931 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2932 currentCompInstance, originResource);
2934 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
2936 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2938 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2939 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2941 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2942 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2944 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2945 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2946 originResource, currentCompInstance, instProperties, allDataTypes.left()
2948 if (addPropertiesValueToRiRes.getStatus() != 200) {
2949 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2952 addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
2958 private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2959 Resource originResource;
2960 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2961 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2962 .getToscaFullElement(currentCompInstance.getComponentUid());
2963 if (getOriginResourceRes.isRight()) {
2964 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2965 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2966 getOriginResourceRes);
2967 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
2968 .value()), currentCompInstance.getComponentUid());
2970 originResource = getOriginResourceRes.left()
2972 originCompMap.put(originResource.getUniqueId(), originResource);
2974 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2976 return originResource;
2979 private void processComponentInstanceCapabilities(
2980 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2981 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2982 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2983 Resource originResource) {
2984 Map<String, List<CapabilityDefinition>> originCapabilities;
2985 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2986 originCapabilities = new HashMap<>();
2987 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2988 originResource.getCapabilities()
2989 .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
2990 uploadComponentInstanceInfo.getCapabilities()
2992 .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
2993 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2995 originCapabilities = originResource.getCapabilities();
2997 instCapabilties.put(currentCompInstance, originCapabilities);
3000 private void updateCapabilityPropertiesValues(
3001 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
3002 Map<String, List<CapabilityDefinition>> originCapabilities,
3003 Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
3004 originCapabilities.values()
3006 .flatMap(Collection::stream)
3007 .filter(c -> newPropertiesMap.containsKey(c.getName()))
3008 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
3013 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
3014 List<UploadCapInfo> capabilities) {
3015 for (UploadCapInfo capability : capabilities) {
3016 if (isNotEmpty(capability.getProperties())) {
3017 newPropertiesMap.put(capability.getName(), capability.getProperties()
3019 .collect(toMap(UploadInfo::getName, p -> p)));
3024 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
3025 List<CapabilityDefinition> capabilities) {
3026 List<CapabilityDefinition> list = capabilities.stream()
3027 .map(CapabilityDefinition::new)
3029 originCapabilities.put(type, list);
3032 private void updatePropertyValues(List<ComponentInstanceProperty> properties,
3033 Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
3034 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
3037 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
3038 Map<String, DataTypeDefinition> allDataTypes) {
3039 String value = null;
3040 List<GetInputValueDataDefinition> getInputs = null;
3041 boolean isValidate = true;
3042 if (null != propertyInfo && propertyInfo.getValue() != null) {
3043 getInputs = propertyInfo.getGet_input();
3044 isValidate = getInputs == null || getInputs.isEmpty();
3046 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
3048 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3049 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3052 property.setValue(value);
3053 return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3056 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
3057 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3058 Either<Resource, StorageOperationStatus> updateRes = null;
3059 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3060 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3061 StorageOperationStatus status = toscaOperationFacade
3062 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
3063 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3065 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
3066 resource.getUniqueId(), status);
3067 updateRes = Either.right(status);
3069 if (updateRes == null) {
3070 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
3071 updatedInstCapabilities, updatedInstRequirements);
3072 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
3073 updatedInstRequirements, resource);
3074 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3076 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
3077 resource.getUniqueId(), status);
3078 updateRes = Either.right(status);
3081 if (updateRes == null) {
3082 updateRes = Either.left(resource);
3087 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
3088 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3089 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
3090 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3092 componentInstances.stream()
3094 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
3095 .getCapabilitiesNamesToUpdate());
3096 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
3097 .getRequirementsNamesToUpdate());
3101 private void fillUpdatedInstRequirements(
3102 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
3103 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3104 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3105 Set<String> updatedReqNames = new HashSet<>();
3106 if (isNotEmpty(requirementsNamesToUpdate)) {
3107 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
3109 updatedRequirements.put(requirements.getKey(), requirements.getValue()
3111 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
3112 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3114 r.setParentName(r.getName());
3115 r.setName(requirementsNamesToUpdate.get(r.getName()));
3116 updatedReqNames.add(r.getName());
3119 .collect(toList()));
3122 if (isNotEmpty(updatedRequirements)) {
3123 updatedInstRequirements.put(instance, updatedRequirements);
3127 private void fillUpdatedInstCapabilities(
3128 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
3129 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3130 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3131 Set<String> updatedCapNames = new HashSet<>();
3132 if (isNotEmpty(capabilitiesNamesToUpdate)) {
3133 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
3135 updatedCapabilities.put(requirements.getKey(), requirements.getValue()
3137 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
3138 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3140 c.setParentName(c.getName());
3141 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
3142 updatedCapNames.add(c.getName());
3145 .collect(toList()));
3148 if (isNotEmpty(updatedCapabilities)) {
3149 updatedInstCapabilties.put(instance, updatedCapabilities);
3153 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
3154 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3155 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3157 ComponentInstance currentCompInstance = null;
3159 for (ComponentInstance compInstance : componentInstancesList) {
3161 if (compInstance.getName()
3162 .equals(nodesInfoValue.getName())) {
3163 currentCompInstance = compInstance;
3169 if (currentCompInstance == null) {
3170 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
3171 BeEcompErrorManager.getInstance()
3172 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
3173 resource.getUniqueId(), ErrorSeverity.ERROR);
3174 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3176 String resourceInstanceId = currentCompInstance.getUniqueId();
3178 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
3180 if (regMap != null) {
3181 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
3184 while (nodesRegValue.hasNext()) {
3185 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3187 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3188 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3189 log.debug("Going to create relation {}", uploadRegInfo.getName());
3190 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
3191 String regName = uploadRegInfo.getName();
3192 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3193 regCapRelDef.setFromNode(resourceInstanceId);
3194 log.debug("try to find available requirement {} ", regName);
3195 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3196 yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
3197 if (eitherReqStatus.isRight()) {
3198 log.debug("failed to find available requirement {} status is {}", regName,
3199 eitherReqStatus.right()
3201 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
3202 return eitherReqStatus.right()
3206 RequirementDefinition validReq = eitherReqStatus.left()
3208 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3209 .getRelationships();
3210 if (reqAndRelationshipPairList == null) {
3211 reqAndRelationshipPairList = new ArrayList<>();
3213 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3214 reqAndRelationshipPair.setRequirement(regName);
3215 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3216 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3217 RelationshipImpl relationship = new RelationshipImpl();
3218 relationship.setType(validReq.getCapability());
3219 reqAndRelationshipPair.setRelationships(relationship);
3221 ComponentInstance currentCapCompInstance = null;
3222 for (ComponentInstance compInstance : componentInstancesList) {
3223 if (compInstance.getName()
3224 .equals(uploadRegInfo.getNode())) {
3225 currentCapCompInstance = compInstance;
3230 if (currentCapCompInstance == null) {
3231 log.debug("The component instance with name {} not found on resource {} ",
3232 uploadRegInfo.getNode(), resource.getUniqueId());
3233 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
3234 BeEcompErrorManager.getInstance()
3235 .logInternalDataError(
3236 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
3237 resource.getUniqueId(), ErrorSeverity.ERROR);
3238 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3240 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3241 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3242 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3243 currentCapCompInstance, uploadRegInfo);
3245 if (aviableCapForRel == null) {
3246 log.debug("aviable capability was not found. req name is {} component instance is {}",
3247 validReq.getName(), currentCapCompInstance.getUniqueId());
3248 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR available capability was not found. req name is: {} component instance is: {}",validReq.getName(),currentCapCompInstance.getUniqueId());
3249 BeEcompErrorManager.getInstance()
3250 .logInternalDataError(
3251 "aviable capability was not found. req name is " + validReq.getName()
3252 + " component instance is " + currentCapCompInstance.getUniqueId(),
3253 resource.getUniqueId(), ErrorSeverity.ERROR);
3254 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3256 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3257 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3258 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3260 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3261 capReqRel.setRelation(reqAndRelationshipPair);
3262 reqAndRelationshipPairList.add(capReqRel);
3263 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3264 relations.add(regCapRelDef);
3267 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3268 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3270 return componentsUtils.getResponseFormat(ActionStatus.OK);
3273 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
3274 Resource originResource, ComponentInstance currentCompInstance,
3275 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3276 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3277 if (MapUtils.isNotEmpty(propMap)) {
3278 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
3279 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3281 if (CollectionUtils.isEmpty(originResource.getInputs())) {
3282 log.debug("failed to find properties ");
3283 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
3284 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
3286 originResource.getInputs()
3287 .forEach(p -> addInput(currPropertiesMap, p));
3288 for (List<UploadPropInfo> propertyList : propMap.values()) {
3289 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
3292 currPropertiesMap.values()
3293 .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
3294 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3298 private void processProperty(Resource resource, ComponentInstance currentCompInstance,
3299 Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
3300 List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
3301 UploadPropInfo propertyInfo = propertyList.get(0);
3302 String propName = propertyInfo.getName();
3303 if (!currPropertiesMap.containsKey(propName)) {
3304 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3305 StatusCode.ERROR,"ERROR failed to find property: {}",propName);
3306 log.debug("failed to find property {} ", propName);
3307 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
3309 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3310 ComponentInstanceInput property = null;
3312 String value = null;
3313 List<GetInputValueDataDefinition> getInputs = null;
3314 boolean isValidate = true;
3315 if (propertyInfo.getValue() != null) {
3316 getInputs = propertyInfo.getGet_input();
3317 isValidate = getInputs == null || getInputs.isEmpty();
3319 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3321 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3322 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3325 property = new ComponentInstanceInput(curPropertyDef, value, null);
3327 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3329 property.setValue(validPropertyVAlue);
3331 if (isNotEmpty(getInputs)) {
3332 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3333 for (GetInputValueDataDefinition getInput : getInputs) {
3334 List<InputDefinition> inputs = resource.getInputs();
3335 if (CollectionUtils.isEmpty(inputs)) {
3336 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3337 StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
3338 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
3339 currentCompInstance.getUniqueId());
3340 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3343 Optional<InputDefinition> optional = inputs.stream()
3344 .filter(p -> p.getName()
3345 .equals(getInput.getInputName()))
3347 if (!optional.isPresent()) {
3348 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3349 StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
3350 log.debug("Failed to find input {} ", getInput.getInputName());
3351 // @@TODO error message
3352 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3354 InputDefinition input = optional.get();
3355 getInput.setInputId(input.getUniqueId());
3356 getInputValues.add(getInput);
3358 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3359 processGetInput(getInputValues, inputs, getInputIndex);
3361 property.setGetInputValues(getInputValues);
3363 instPropList.add(property);
3364 // delete overriden property
3365 currPropertiesMap.remove(property.getName());
3368 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
3369 GetInputValueDataDefinition getInputIndex) {
3370 Optional<InputDefinition> optional;
3371 if (getInputIndex != null) {
3372 optional = inputs.stream()
3373 .filter(p -> p.getName()
3374 .equals(getInputIndex.getInputName()))
3376 if (!optional.isPresent()) {
3377 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3378 // @@TODO error message
3379 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3381 InputDefinition inputIndex = optional.get();
3382 getInputIndex.setInputId(inputIndex.getUniqueId());
3383 getInputValues.add(getInputIndex);
3387 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
3388 String propName = prop.getName();
3389 if (!currPropertiesMap.containsKey(propName)) {
3390 currPropertiesMap.put(propName, prop);
3394 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3395 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
3396 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3398 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3399 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
3401 List<PropertyDefinition> listFromMap = originResource.getProperties();
3402 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3403 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3404 StatusCode.ERROR,"ERROR Failed to find properties");
3405 log.debug("failed to find properties");
3406 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3408 if (listFromMap == null || listFromMap.isEmpty()) {
3409 return componentsUtils.getResponseFormat(ActionStatus.OK);
3411 for (PropertyDefinition prop : listFromMap) {
3412 String propName = prop.getName();
3413 if (!currPropertiesMap.containsKey(propName)) {
3414 currPropertiesMap.put(propName, prop);
3417 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3418 if (propMap != null && propMap.size() > 0) {
3419 for (List<UploadPropInfo> propertyList : propMap.values()) {
3421 UploadPropInfo propertyInfo = propertyList.get(0);
3422 String propName = propertyInfo.getName();
3423 if (!currPropertiesMap.containsKey(propName)) {
3424 log.debug("failed to find property {} ", propName);
3425 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
3426 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3428 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3429 ComponentInstanceProperty property = null;
3431 String value = null;
3432 List<GetInputValueDataDefinition> getInputs = null;
3433 boolean isValidate = true;
3434 if (propertyInfo.getValue() != null) {
3435 getInputs = propertyInfo.getGet_input();
3436 isValidate = getInputs == null || getInputs.isEmpty();
3438 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3440 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3441 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3444 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3446 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3447 property.setValue(validatePropValue);
3449 if (getInputs != null && !getInputs.isEmpty()) {
3450 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3451 for (GetInputValueDataDefinition getInput : getInputs) {
3452 List<InputDefinition> inputs = resource.getInputs();
3453 if (inputs == null || inputs.isEmpty()) {
3454 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
3455 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
3456 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
3458 .map(GetInputValueDataDefinition::getInputName)
3462 Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
3463 if (inputEither.isRight()) {
3464 throw inputEither.right().value();
3466 InputDefinition input = inputEither.left().value();
3467 getInput.setInputId(input.getUniqueId());
3468 getInputValues.add(getInput);
3470 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3471 if (getInputIndex != null) {
3472 Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
3474 if (inputEither.isRight()) {
3475 throw newInputEither.right().value();
3477 InputDefinition newInput = newInputEither.left().value();
3478 getInputIndex.setInputId(newInput.getUniqueId());
3480 getInputValues.add(getInputIndex);
3485 property.setGetInputValues(getInputValues);
3487 instPropList.add(property);
3488 // delete overriden property
3489 currPropertiesMap.remove(property.getName());
3492 // add rest of properties
3493 if (!currPropertiesMap.isEmpty()) {
3494 for (PropertyDefinition value : currPropertiesMap.values()) {
3495 instPropList.add(new ComponentInstanceProperty(value));
3498 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3499 return componentsUtils.getResponseFormat(ActionStatus.OK);
3502 // US740820 Relate RIs according to capability name
3503 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3504 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3505 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
3506 .equals(uploadReqInfo.getCapabilityName())) {// get
3510 return findAvailableCapability(validReq, currentCapCompInstance);
3512 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3515 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3516 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3517 CapabilityDefinition cap = null;
3518 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3519 if (!capMap.containsKey(validReq.getCapability())) {
3522 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
3524 .filter(p -> p.getName()
3525 .equals(uploadReqInfo.getCapabilityName()))
3527 if (!capByName.isPresent()) {
3530 cap = capByName.get();
3532 if (isBoundedByOccurrences(cap)) {
3533 String leftOccurrences = cap.getLeftOccurrences();
3534 int left = Integer.parseInt(leftOccurrences);
3537 cap.setLeftOccurrences(String.valueOf(left));
3545 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
3546 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
3547 if (capMap.containsKey(validReq.getCapability())) {
3548 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3550 for (CapabilityDefinition cap : capList) {
3551 if (isBoundedByOccurrences(cap)) {
3552 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
3553 : cap.getMaxOccurrences();
3554 int left = Integer.parseInt(leftOccurrences);
3557 cap.setLeftOccurrences(String.valueOf(left));
3568 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
3569 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
3570 .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
3573 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3574 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3576 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3577 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3578 RequirementDefinition validRegDef = null;
3580 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3581 for (RequirementDefinition reqDef : entry.getValue()) {
3582 if (reqDef.getName()
3584 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3585 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3586 String leftOccurrences = reqDef.getLeftOccurrences();
3587 if (leftOccurrences == null) {
3588 leftOccurrences = reqDef.getMaxOccurrences();
3590 int left = Integer.parseInt(leftOccurrences);
3593 reqDef.setLeftOccurrences(String.valueOf(left));
3594 validRegDef = reqDef;
3600 validRegDef = reqDef;
3606 if (validRegDef != null) {
3611 for (RequirementDefinition reqDef : list) {
3612 if (reqDef.getName()
3614 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3615 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3616 String leftOccurrences = reqDef.getLeftOccurrences();
3617 if (leftOccurrences == null) {
3618 leftOccurrences = reqDef.getMaxOccurrences();
3620 int left = Integer.parseInt(leftOccurrences);
3623 reqDef.setLeftOccurrences(String.valueOf(left));
3624 validRegDef = reqDef;
3630 validRegDef = reqDef;
3636 if (validRegDef == null) {
3637 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3638 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3639 return Either.right(responseFormat);
3641 return Either.left(validRegDef);
3644 private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
3645 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
3647 Either<Resource, ResponseFormat> eitherResource;
3648 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3649 if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3650 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3651 throw new ByResponseFormatComponentException(responseFormat);
3653 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3654 nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
3656 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3657 uploadResInstancesMap.values()
3658 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
3659 existingNodeTypesByResourceNames, resourcesInstancesMap));
3660 if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
3661 Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
3663 .collect(toMap(Resource::getUniqueId, r -> r));
3664 oldResource.getComponentInstances()
3666 .filter(i -> !i.isCreatedFromCsar())
3667 .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
3668 getOriginResource(existingNodeTypesByUids, uiInst)));
3671 if (isNotEmpty(resourcesInstancesMap)) {
3673 toscaOperationFacade.associateComponentInstancesToComponent(resource,
3674 resourcesInstancesMap, false, oldResource != null);
3675 } catch (StorageException exp) {
3676 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
3677 log.debug("Failed to add component instances to container component {}", resource.getName());
3678 ResponseFormat responseFormat = componentsUtils
3679 .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
3680 eitherResource = Either.right(responseFormat);
3681 throw new ByResponseFormatComponentException(eitherResource.right().value());
3685 if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
3686 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3687 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3688 BeEcompErrorManager.getInstance()
3689 .logBeDaoSystemError(
3690 "Error when create resource instance from csar. ComponentInstances list empty");
3691 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3696 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3697 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
3698 Map<ComponentInstance, Resource> resourcesInstancesMap) {
3699 Either<Resource, ResponseFormat> eitherResource;
3700 log.debug("*************Going to create resource instances {}", yamlName);
3701 // updating type if the type is node type name - we need to take the
3703 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3704 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3705 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
3706 .getToscaResourceName());
3708 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3709 existingnodeTypeMap);
3711 ComponentInstance componentInstance = new ComponentInstance();
3712 componentInstance.setComponentUid(refResource.getUniqueId());
3713 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3714 if(directives != null && !directives.isEmpty()) {
3715 componentInstance.setDirectives(new ArrayList<>(directives));
3717 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3718 if (uploadNodeFilterInfo != null){
3719 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3720 componentInstance.getUniqueId()));
3722 ComponentTypeEnum containerComponentType = resource.getComponentType();
3723 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3724 if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3725 && isNotEmpty(refResource.getCapabilities())) {
3726 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3727 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3728 refResource.getUniqueId(), refResource.getCapabilities(),
3729 uploadComponentInstanceInfo.getCapabilities());
3730 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3733 if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
3734 Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
3735 Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
3736 Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
3737 .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
3738 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
3739 Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
3740 for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
3741 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
3742 to.setFile(entry.getValue().getFile());
3743 to.setType(entry.getValue().getType());
3744 toscaArtifacts.put(entry.getKey(), to);
3746 componentInstance.setToscaArtifacts(toscaArtifacts);
3749 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3750 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
3751 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3752 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3753 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3755 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3756 componentInstance.setName(uploadComponentInstanceInfo.getName());
3757 componentInstance.setIcon(origResource.getIcon());
3758 componentInstance.setCreatedFrom(CreatedFrom.CSAR);
3759 resourcesInstancesMap.put(componentInstance, origResource);
3762 private ComponentParametersView getComponentWithInstancesFilter() {
3763 ComponentParametersView parametersView = new ComponentParametersView();
3764 parametersView.disableAll();
3765 parametersView.setIgnoreComponentInstances(false);
3766 parametersView.setIgnoreInputs(false);
3767 // inputs are read when creating
3768 // property values on instances
3769 parametersView.setIgnoreUsers(false);
3770 return parametersView;
3773 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3774 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3775 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3776 if (originCapabilities.containsKey(currEntry.getKey())) {
3777 currEntry.getValue()
3779 .forEach(cap -> cap.setType(currEntry.getKey()));
3782 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3783 capabilities.getValue()
3786 if (uploadedCapabilities.containsKey(cap.getName())) {
3787 uploadedCapabilities.get(cap.getName())
3790 c.setName(cap.getName());
3791 c.setType(cap.getType());
3798 private Resource validateResourceInstanceBeforeCreate(String yamlName,
3799 UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
3802 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
3803 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3804 Resource refResource;
3805 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3806 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3808 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3809 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3810 if (findResourceEither.isRight()) {
3812 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type {}",
3813 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3814 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3816 refResource = findResourceEither.left().value();
3817 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3819 String componentState = refResource.getComponentMetadataDefinition()
3820 .getMetadataDataDefinition()
3822 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3824 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3825 refResource.getName(), componentState);
3826 throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
3827 refResource.getComponentType().getValue(),refResource.getName(), componentState);
3830 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3831 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3832 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3833 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3838 public Resource propagateStateToCertified(User user, Resource resource,
3839 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3840 boolean forceCertificationAllowed) {
3842 boolean failed = false;
3844 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3845 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3846 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3848 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3849 Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
3850 resource, user, false, inTransaction, needLock, false);
3853 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3854 } catch (ComponentException e) {
3856 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3860 BeEcompErrorManager.getInstance()
3861 .logBeSystemError("Change LifecycleState - Certify");
3862 if (!inTransaction) {
3863 janusGraphDao.rollback();
3865 } else if (!inTransaction) {
3866 janusGraphDao.commit();
3871 private Resource nodeFullCertification(String uniqueId, User user,
3872 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3873 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
3874 inTransaction, needLock);
3875 if(resourceResponse.isRight()){
3876 throw new ByResponseFormatComponentException(resourceResponse.right().value());
3878 return resourceResponse.left().value();
3881 private Resource nodeForceCertification(Resource resource, User user,
3882 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3883 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3887 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
3889 final boolean isNormative,
3890 final boolean isInTransaction,
3891 final boolean needLock,
3892 final CsarInfo csarInfo,
3893 final String nodeName,
3894 final boolean isNested) {
3896 ImmutablePair<Resource, ActionStatus> result = null;
3897 // check if resource already exists (search by tosca name = type)
3898 final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3899 final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3900 .getLatestByToscaResourceName(resource.getToscaResourceName());
3902 if (latestByToscaName.isLeft()) {
3903 Resource foundResource = latestByToscaName.left().value();
3904 // we don't allow updating names of top level types
3905 if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
3906 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3907 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3908 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3909 foundResource.getName(), resource.getToscaResourceName());
3910 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3911 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3912 throwComponentException(responseFormat);
3914 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3915 } else if (isNotFound(latestByToscaName)) {
3916 if (isNestedResource) {
3917 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
3918 isNested, nodeName);
3920 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3923 StorageOperationStatus status = latestByToscaName.right().value();
3924 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3925 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
3926 .convertFromStorageResponse(latestByToscaName.right().value()), resource);
3927 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3928 throwComponentException(responseFormat);
3933 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3934 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3937 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
3939 final boolean isNormative,
3940 final boolean isInTransaction,
3941 final boolean needLock,
3942 final CsarInfo csarInfo,
3943 final boolean isNested,
3944 final String nodeName) {
3945 final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3946 .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
3947 .name(), csarInfo.getVfResourceName(), nodeName).getRight());
3948 if (latestByToscaName.isLeft()) {
3949 final Resource nestedResource = (Resource) latestByToscaName.left().value();
3950 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3951 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
3952 resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3953 if (eitherValidation.isRight()) {
3954 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3956 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3958 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3962 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3963 return getResourceEither.isRight() && getResourceEither.right()
3964 .value() == StorageOperationStatus.NOT_FOUND;
3967 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
3968 boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3969 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3970 validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3971 final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
3973 Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
3974 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
3975 ASDCKpiApi.countImportResourcesKPI();
3976 return resourcePair;
3979 public boolean isResourceExist(String resourceName) {
3980 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3981 return latestByName.isLeft();
3984 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
3985 Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
3986 String lockedResourceId = oldResource.getUniqueId();
3987 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3988 oldResource.getVersion(), oldResource.getLifecycleState());
3989 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3991 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3992 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3993 mergeOldResourceMetadataWithNew(oldResource, newResource);
3995 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3996 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3997 // contact info normalization
3998 newResource.setContactId(newResource.getContactId().toLowerCase());
3999 PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
4000 // non-updatable fields
4001 newResource.setCreatorUserId(user.getUserId());
4002 newResource.setCreatorFullName(user.getFullName());
4003 newResource.setLastUpdaterUserId(user.getUserId());
4004 newResource.setLastUpdaterFullName(user.getFullName());
4005 newResource.setUniqueId(oldResource.getUniqueId());
4006 newResource.setVersion(oldResource.getVersion());
4007 newResource.setInvariantUUID(oldResource.getInvariantUUID());
4008 newResource.setLifecycleState(oldResource.getLifecycleState());
4009 newResource.setUUID(oldResource.getUUID());
4010 newResource.setNormalizedName(oldResource.getNormalizedName());
4011 newResource.setSystemName(oldResource.getSystemName());
4012 if (oldResource.getCsarUUID() != null) {
4013 newResource.setCsarUUID(oldResource.getCsarUUID());
4015 if (oldResource.getImportedToscaChecksum() != null) {
4016 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
4018 newResource.setAbstract(oldResource.isAbstract());
4020 if (CollectionUtils.isEmpty(newResource.getDerivedFrom())){
4021 newResource.setDerivedFrom(oldResource.getDerivedFrom());
4023 if (CollectionUtils.isEmpty(newResource.getDataTypes())){
4024 newResource.setDataTypes(oldResource.getDataTypes());
4026 if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())){
4027 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
4029 if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())){
4030 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
4033 // created without tosca artifacts - add the placeholders
4034 if (MapUtils.isEmpty(newResource.getToscaArtifacts())){
4035 setToscaArtifactsPlaceHolders(newResource, user);
4038 if (MapUtils.isEmpty(newResource.getInterfaces())){
4039 newResource.setInterfaces(oldResource.getInterfaces());
4041 if (CollectionUtils.isEmpty(newResource.getAttributes())) {
4042 newResource.setAttributes(oldResource.getAttributes());
4045 if (CollectionUtils.isEmpty(newResource.getProperties())) {
4046 newResource.setProperties(oldResource.getProperties());
4049 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
4051 if (overrideResource.isRight()) {
4052 ResponseFormat responseFormat = componentsUtils
4053 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
4054 .value()), newResource);
4055 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
4057 throwComponentException(responseFormat);
4059 updateCatalog(overrideResource.left()
4060 .value(), ChangeTypeEnum.LIFECYCLE);
4062 log.debug("Resource updated successfully!!!");
4063 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4064 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4065 ResourceVersionInfo.newBuilder()
4066 .state(oldResource.getLifecycleState()
4068 .version(oldResource.getVersion())
4071 resourcePair = new ImmutablePair<>(overrideResource.left()
4072 .value(), ActionStatus.OK);
4073 return resourcePair;
4075 if (resourcePair == null) {
4076 BeEcompErrorManager.getInstance()
4077 .logBeSystemError("Change LifecycleState - Certify");
4078 janusGraphDao.rollback();
4079 } else if (!inTransaction) {
4080 janusGraphDao.commit();
4083 log.debug("unlock resource {}", lockedResourceId);
4084 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4091 * Merge old resource with new. Keep old category and vendor name without
4094 * @param oldResource
4095 * @param newResource
4097 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4099 // keep old category and vendor name without change
4100 // merge the rest of the resource metadata
4101 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4102 newResource.setTags(oldResource.getTags());
4105 if (newResource.getDescription() == null) {
4106 newResource.setDescription(oldResource.getDescription());
4109 if (newResource.getVendorRelease() == null) {
4110 newResource.setVendorRelease(oldResource.getVendorRelease());
4113 if (newResource.getResourceVendorModelNumber() == null) {
4114 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4117 if (newResource.getContactId() == null) {
4118 newResource.setContactId(oldResource.getContactId());
4121 newResource.setCategories(oldResource.getCategories());
4122 if (newResource.getVendorName() == null) {
4123 newResource.setVendorName(oldResource.getVendorName());
4125 List<GroupDefinition>oldForUpdate = oldResource.getGroups();
4126 if(CollectionUtils.isNotEmpty(oldForUpdate)){
4127 List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
4129 groupForUpdate.stream().filter(group -> group.isVspOriginated())
4130 .forEach(group -> group.setName(group.getInvariantName()));
4132 newResource.setGroups(groupForUpdate);
4136 if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
4137 ResourceTypeEnum updatedResourceType = newResource.getResourceType();
4138 Component derivedFromResource = getParentComponent(newResource);
4139 if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
4140 Resource parentResource = (Resource) derivedFromResource;
4141 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
4142 parentResource.getResourceType() != updatedResourceType) {
4143 BeEcompErrorManager.getInstance()
4144 .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
4145 ErrorSeverity.ERROR);
4146 log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
4147 newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
4148 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
4155 private Component getParentComponent(Resource newResource) {
4156 String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
4157 Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
4158 if(latestByToscaResourceName.isRight()){
4159 BeEcompErrorManager.getInstance()
4160 .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
4161 log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
4162 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
4164 return latestByToscaResourceName.left().value();
4167 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
4168 boolean inTransaction, boolean needLock) {
4170 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
4172 return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4173 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
4175 .on(response -> failOnChangeState(response, user, oldResource, newResource));
4180 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
4181 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
4182 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4183 ResourceVersionInfo.newBuilder()
4184 .state(oldResource.getLifecycleState()
4186 .version(oldResource.getVersion())
4188 throw new ByResponseFormatComponentException(response);
4191 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
4192 boolean inTransaction, CsarInfo csarInfo) {
4194 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4195 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4196 validateLifecycleTypesCreate(user, resource, actionEnum);
4197 validateResourceType(user, resource, actionEnum);
4198 resource.setCreatorUserId(user.getUserId());
4199 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4200 resource.setContactId(resource.getContactId()
4202 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4203 String resourceSystemName;
4204 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4205 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4207 resourceSystemName = resource.getSystemName();
4209 resource.setToscaResourceName(CommonBeUtils
4210 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4213 // Generate invariant UUID - must be here and not in operation since it
4214 // should stay constant during clone
4216 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4217 resource.setInvariantUUID(invariantUUID);
4222 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4223 AuditingActionEnum actionEnum) {
4224 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4225 if (resource.getResourceType() == null) {
4226 log.debug("Invalid resource type for resource");
4227 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4228 eitherResult = Either.right(errorResponse);
4229 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4231 return eitherResult;
4234 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4235 AuditingActionEnum actionEnum) {
4236 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4237 if (resource.getInterfaces() != null && resource.getInterfaces()
4239 log.debug("validate interface lifecycle Types Exist");
4240 Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
4243 while (intItr.hasNext() && eitherResult.isLeft()) {
4244 InterfaceDefinition interfaceDefinition = intItr.next();
4245 String intType = interfaceDefinition.getUniqueId();
4246 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4247 .getInterface(intType);
4248 if (eitherCapTypeFound.isRight()) {
4249 if (eitherCapTypeFound.right()
4250 .value() == StorageOperationStatus.NOT_FOUND) {
4251 BeEcompErrorManager.getInstance()
4252 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
4253 "Interface", intType);
4254 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4255 intType, resource.getName());
4256 BeEcompErrorManager.getInstance()
4257 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4258 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
4263 ResponseFormat errorResponse = componentsUtils
4264 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4265 eitherResult = Either.right(errorResponse);
4266 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4271 return eitherResult;
4274 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4275 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4276 boolean inTransaction) {
4278 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4279 if (resource.getCapabilities() != null && resource.getCapabilities()
4281 log.debug("validate capability Types Exist - capabilities section");
4283 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
4286 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4287 eitherResult, typeEntry, inTransaction);
4288 if (eitherResult.isRight()) {
4289 return Either.right(eitherResult.right()
4295 if (resource.getRequirements() != null && resource.getRequirements()
4297 log.debug("validate capability Types Exist - requirements section");
4298 for (String type : resource.getRequirements()
4300 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4301 resource.getRequirements()
4303 actionEnum, eitherResult, type, inTransaction);
4304 if (eitherResult.isRight()) {
4305 return Either.right(eitherResult.right()
4311 return eitherResult;
4314 // @param typeObject- the object to which the validation is done
4315 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4316 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4317 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4318 boolean inTransaction) {
4319 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4320 .getCapabilityType(type, inTransaction);
4321 if (eitherCapTypeFound.isRight()) {
4322 if (eitherCapTypeFound.right()
4323 .value() == StorageOperationStatus.NOT_FOUND) {
4324 BeEcompErrorManager.getInstance()
4325 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4327 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4328 resource.getName());
4329 BeEcompErrorManager.getInstance()
4330 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4332 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
4335 ResponseFormat errorResponse = null;
4337 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4339 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4342 eitherResult = Either.right(errorResponse);
4343 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4345 return eitherResult;
4348 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4349 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4350 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4351 boolean inTransaction) {
4352 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4353 .getCapabilityType(typeEntry.getKey(), inTransaction);
4354 if (eitherCapTypeFound.isRight()) {
4355 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4356 BeEcompErrorManager.getInstance()
4357 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4358 typeEntry.getKey());
4359 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4360 typeEntry.getKey(), resource.getName());
4361 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4363 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4364 eitherCapTypeFound.right().value().name());
4365 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4366 typeEntry.getKey());
4367 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4368 return Either.right(errorResponse);
4370 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4371 if (capabilityTypeDefinition.getProperties() != null) {
4372 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4373 List<ComponentInstanceProperty> properties = capDef.getProperties();
4374 List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
4375 if (properties == null || properties.isEmpty()) {
4376 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4377 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4378 changedProperties.add(newProp);
4381 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4382 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4383 PropertyDefinition propFromDef = prop.getValue();
4384 boolean propFound = false;
4385 for (ComponentInstanceProperty cip : properties) {
4386 if (propFromDef.getName().equals(cip.getName())) {
4387 //merge property value and property description only, ignore other fields
4388 if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
4389 propFromDef.setDescription(cip.getDescription());
4391 propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
4392 if(cip.getValue() != null){
4393 propFromDef.setValue(cip.getValue());
4395 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4397 properties.remove(cip);
4402 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4405 if (!propsToAdd.isEmpty()) {
4406 changedProperties.addAll(propsToAdd);
4409 capDef.setProperties(changedProperties);
4412 return eitherResult;
4415 public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
4416 boolean isNormative, boolean inTransaction) {
4419 // lock new resource name in order to avoid creation resource with same
4421 Resource createdResource = null;
4422 if (!inTransaction) {
4423 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4425 if (lockResult.isRight()) {
4426 ResponseFormat responseFormat = lockResult.right().value();
4427 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4428 throw new ByResponseFormatComponentException(responseFormat);
4431 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4434 if (resource.deriveFromGeneric()) {
4435 handleResourceGenericType(resource);
4437 createdResource = createResourceTransaction(resource, user, isNormative);
4438 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4439 createdResource, actionEnum);
4440 ASDCKpiApi.countCreatedResourcesKPI();
4441 } catch (ComponentException e) {
4442 ResponseFormat responseFormat = e.getResponseFormat() == null
4443 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
4444 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4446 } catch (StorageException e) {
4447 ResponseFormat responseFormat = componentsUtils
4448 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
4449 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4452 if (!inTransaction) {
4453 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4454 NodeTypeEnum.Resource);
4457 return createdResource;
4460 private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
4461 // validate resource name uniqueness
4462 log.debug("validate resource name");
4463 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4464 resource.getName(), resource.getResourceType(), resource.getComponentType());
4465 if (eitherValidation.isRight()) {
4466 loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
4467 StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
4468 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4469 eitherValidation.right()
4471 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
4474 if (eitherValidation.left()
4476 log.debug("resource with name: {}, already exists", resource.getName());
4477 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
4478 StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
4479 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4480 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4483 log.debug("send resource {} to dao for create", resource.getName());
4485 createArtifactsPlaceHolderData(resource, user);
4488 log.debug("enrich resource with creator, version and state");
4489 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4490 resource.setVersion(INITIAL_VERSION);
4491 resource.setHighestVersion(true);
4492 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4493 resource.setAbstract(false);
4496 return toscaOperationFacade.createToscaComponent(resource)
4498 .on(r -> throwComponentExceptionByResource(r, resource));
4501 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
4502 ResponseFormat responseFormat = componentsUtils
4503 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
4504 throw new ByResponseFormatComponentException(responseFormat);
4507 private void createArtifactsPlaceHolderData(Resource resource, User user) {
4508 // create mandatory artifacts
4510 // TODO it must be removed after that artifact uniqueId creation will be
4511 // moved to ArtifactOperation
4513 setInformationalArtifactsPlaceHolder(resource, user);
4514 setDeploymentArtifactsPlaceHolder(resource, user);
4515 setToscaArtifactsPlaceHolders(resource, user);
4518 @SuppressWarnings("unchecked")
4520 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4521 Resource resource = (Resource) component;
4522 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4523 if (artifactMap == null) {
4524 artifactMap = new HashMap<>();
4526 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4528 .getDeploymentResourceArtifacts();
4529 if (deploymentResourceArtifacts != null) {
4530 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
4531 deploymentResourceArtifacts
4532 .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
4534 resource.setDeploymentArtifacts(artifactMap);
4537 private void processDeploymentResourceArtifacts(User user, Resource resource,
4538 Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
4539 Map<String, Object> artifactDetails = (Map<String, Object>) v;
4540 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4541 if (object != null) {
4542 List<String> artifactTypes = (List<String>) object;
4543 if (!artifactTypes.contains(resource.getResourceType()
4548 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
4550 if (artifactsBusinessLogic != null) {
4551 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4552 resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
4553 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
4554 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4559 @SuppressWarnings("unchecked")
4560 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4561 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4562 if (artifactMap == null) {
4563 artifactMap = new HashMap<>();
4565 String resourceUniqueId = resource.getUniqueId();
4566 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
4568 .getExcludeResourceCategory();
4569 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
4571 .getExcludeResourceType();
4572 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4574 .getInformationalResourceArtifacts();
4575 List<CategoryDefinition> categories = resource.getCategories();
4576 boolean isCreateArtifact = true;
4577 if (exludeResourceCategory != null) {
4578 String category = categories.get(0)
4580 isCreateArtifact = exludeResourceCategory.stream()
4581 .noneMatch(e -> e.equalsIgnoreCase(category));
4583 if (isCreateArtifact && exludeResourceType != null) {
4584 String resourceType = resource.getResourceType()
4586 isCreateArtifact = exludeResourceType.stream()
4587 .noneMatch(e -> e.equalsIgnoreCase(resourceType));
4589 if (informationalResourceArtifacts != null && isCreateArtifact) {
4590 Set<String> keys = informationalResourceArtifacts.keySet();
4591 for (String informationalResourceArtifactName : keys) {
4592 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4593 .get(informationalResourceArtifactName);
4594 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4595 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4596 ArtifactGroupTypeEnum.INFORMATIONAL);
4597 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4601 resource.setArtifacts(artifactMap);
4611 public ResponseFormat deleteResource(String resourceId, User user) {
4612 ResponseFormat responseFormat;
4613 validateUserExists(user);
4615 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4616 if (resourceStatus.isRight()) {
4617 log.debug("failed to get resource {}", resourceId);
4618 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4622 Resource resource = resourceStatus.left()
4625 StorageOperationStatus result = StorageOperationStatus.OK;
4626 lockComponent(resourceId, resource, "Mark resource to delete");
4629 result = markComponentToDelete(resource);
4630 if (result == StorageOperationStatus.OK) {
4631 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4633 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4634 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4636 return responseFormat;
4639 if (result == null || result != StorageOperationStatus.OK) {
4640 janusGraphDao.rollback();
4642 janusGraphDao.commit();
4644 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
4649 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
4650 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4651 validateUserExists(user);
4652 Resource resource = null;
4653 StorageOperationStatus result = StorageOperationStatus.OK;
4654 boolean failed = false;
4657 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
4658 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
4659 if (resourceStatus.isRight()) {
4660 log.debug("failed to get resource {} version {}", resourceName, version);
4661 return componentsUtils
4662 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4663 .value()), resourceName);
4666 resource = resourceStatus.left()
4670 janusGraphDao.commit();
4672 if (resource != null) {
4673 lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
4675 result = markComponentToDelete(resource);
4676 if (result != StorageOperationStatus.OK) {
4677 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4678 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4679 return responseFormat;
4681 }catch (ComponentException e){
4685 if (failed || result == null || result != StorageOperationStatus.OK) {
4686 janusGraphDao.rollback();
4688 janusGraphDao.commit();
4690 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
4693 return responseFormat;
4696 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
4699 validateUserExists(user);
4702 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
4703 if (storageStatus.isRight()) {
4704 log.debug("failed to get resource by id {}", resourceId);
4705 return Either.right(componentsUtils
4706 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
4707 .value()), resourceId));
4709 if (!(storageStatus.left()
4710 .value() instanceof Resource)) {
4711 return Either.right(componentsUtils.getResponseFormatByResource(
4712 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4714 return Either.left(storageStatus.left()
4719 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4722 validateUserExists(userId);
4724 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4725 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4726 if (getResource.isRight()) {
4727 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4728 return Either.right(componentsUtils
4729 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
4730 .value()), resourceName));
4732 return Either.left(getResource.left()
4737 * updateResourceMetadata
4740 * - modifier data (userId)
4741 * @param inTransaction
4743 * @param resourceIdToUpdate
4744 * - the resource identifier
4745 * @param newResource
4746 * @return Either<Resource , responseFormat>
4748 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
4749 User user, boolean inTransaction) {
4751 validateUserExists(user.getUserId());
4753 log.debug("Get resource with id {}", resourceIdToUpdate);
4754 boolean needToUnlock = false;
4757 if (currentResource == null) {
4758 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4759 .getToscaElement(resourceIdToUpdate);
4760 if (storageStatus.isRight()) {
4761 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4762 componentsUtils.convertFromStorageResponse(storageStatus.right()
4767 currentResource = storageStatus.left()
4770 // verify that resource is checked-out and the user is the last
4772 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4773 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4777 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4778 NodeTypeEnum.Resource);
4779 if (lockResult != StorageOperationStatus.OK) {
4780 BeEcompErrorManager.getInstance()
4781 .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
4782 resourceIdToUpdate);
4783 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4784 ResponseFormat responseFormat = componentsUtils
4785 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4786 throw new ByResponseFormatComponentException(responseFormat);
4789 needToUnlock = true;
4791 // critical section starts here
4792 // convert json to object
4794 // Update and updated resource must have a non-empty "derivedFrom"
4796 // This code is not called from import resources, because of root
4797 // VF "derivedFrom" should be null (or ignored)
4798 if (ModelConverter.isAtomicComponent(currentResource)) {
4799 validateDerivedFromNotEmpty(null, newResource, null);
4800 validateDerivedFromNotEmpty(null, currentResource, null);
4802 newResource.setDerivedFrom(null);
4805 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4806 user, currentResource, false, true);
4807 if (dataModelResponse.isRight()) {
4808 log.debug("failed to update resource metadata!!!");
4809 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4812 log.debug("Resource metadata updated successfully!!!");
4813 return dataModelResponse.left()
4816 } catch (ComponentException | StorageException e) {
4817 rollback(inTransaction, newResource, null, null);
4820 if (!inTransaction) {
4821 janusGraphDao.commit();
4824 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4829 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4830 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4831 updateVfModuleGroupsNames(currentResource, newResource);
4832 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4833 // Setting last updater and uniqueId
4834 newResource.setContactId(newResource.getContactId()
4836 newResource.setLastUpdaterUserId(user.getUserId());
4837 newResource.setUniqueId(resourceIdToUpdate);
4838 // Cannot set highest version through UI
4839 newResource.setHighestVersion(currentResource.isHighestVersion());
4840 newResource.setCreationDate(currentResource.getCreationDate());
4842 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4843 newResource, user.getUserId(), inTransaction);
4845 if (processUpdateOfDerivedFrom.isRight()) {
4846 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4847 return Either.right(processUpdateOfDerivedFrom.right()
4851 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4852 if (isNotEmpty(newResource.getGroups())) {
4853 for (GroupDefinition group : newResource.getGroups()) {
4854 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
4855 groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
4856 .getMetadataDataDefinition()
4857 .getUniqueId(), user, newResource.getComponentType(), group, true, false);
4861 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4862 .updateToscaElement(newResource);
4864 if (dataModelResponse.isRight()) {
4865 ResponseFormat responseFormat = componentsUtils
4866 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
4867 .value()), newResource);
4868 return Either.right(responseFormat);
4869 } else if (dataModelResponse.left()
4871 log.debug("No response from updateResource");
4872 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4874 return Either.left(dataModelResponse.left()
4878 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4879 if (currentResource.getGroups() != null && !currentResource.getName()
4880 .equals(newResource.getName())) {
4881 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4883 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4885 newResource.setGroups(updatedGroups);
4889 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4890 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4891 if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
4892 .equals(DEFAULT_GROUP_VF_MODULE)) {
4893 String prefix = updatedGroup.getName()
4894 .substring(0, replacePattern.length());
4895 String newGroupName = updatedGroup.getName()
4896 .replaceFirst(prefix, with);
4897 updatedGroup.setName(newGroupName);
4899 return updatedGroup;
4903 * validateResourceFieldsBeforeCreate
4906 * - modifier data (userId)
4908 private void validateResourceFieldsBeforeCreate(User user, Resource resource,
4909 AuditingActionEnum actionEnum, boolean inTransaction) {
4910 componentValidator.validate(user, resource, actionEnum);
4911 // validate category
4912 log.debug("validate category");
4913 validateCategory(user, resource, actionEnum, inTransaction);
4914 // validate vendor name & release & model number
4915 log.debug("validate vendor name");
4916 validateVendorName(user, resource, actionEnum);
4917 log.debug("validate vendor release");
4918 validateVendorReleaseName(user, resource, actionEnum);
4919 log.debug("validate resource vendor model number");
4920 validateResourceVendorModelNumber(user, resource, actionEnum);
4922 log.debug("validate cost");
4923 validateCost(resource);
4924 // validate licenseType
4925 log.debug("validate licenseType");
4926 validateLicenseType(user, resource, actionEnum);
4927 // validate template (derived from)
4928 log.debug("validate derived from");
4929 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4930 resource.setDerivedFrom(null);
4932 validateDerivedFromExist(user, resource, actionEnum);
4933 // warn about non-updatable fields
4934 checkComponentFieldsForOverrideAttempt(resource);
4935 String currentCreatorFullName = resource.getCreatorFullName();
4936 if (currentCreatorFullName != null) {
4937 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4940 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4941 if (currentLastUpdaterFullName != null) {
4942 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4945 Long currentLastUpdateDate = resource.getLastUpdateDate();
4946 if (currentLastUpdateDate != null) {
4947 log.debug("Resource last update date is automatically set and cannot be updated");
4950 Boolean currentAbstract = resource.isAbstract();
4951 if (currentAbstract != null) {
4952 log.debug("Resource abstract is automatically set and cannot be updated");
4957 * validateResourceFieldsBeforeUpdate
4959 * @param currentResource
4960 * - Resource object to validate
4963 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4964 boolean inTransaction, boolean isNested) {
4965 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4966 warnNonEditableFields(currentResource, updateInfoResource);
4969 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4970 String currentResourceVersion = currentResource.getVersion();
4971 String updatedResourceVersion = updateInfoResource.getVersion();
4973 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4974 log.debug("Resource version is automatically set and cannot be updated");
4977 String currentCreatorUserId = currentResource.getCreatorUserId();
4978 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4980 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4981 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4984 String currentCreatorFullName = currentResource.getCreatorFullName();
4985 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4987 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4988 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4991 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4992 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4994 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4995 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4998 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4999 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
5001 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
5002 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
5004 Long currentCreationDate = currentResource.getCreationDate();
5005 Long updatedCreationDate = updateInfoResource.getCreationDate();
5007 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
5008 log.debug("Resource Creation date is automatically set and cannot be updated");
5011 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
5012 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
5014 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
5015 log.debug("Resource last update date is automatically set and cannot be updated");
5018 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
5019 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
5021 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
5022 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
5025 Boolean currentAbstract = currentResource.isAbstract();
5026 Boolean updatedAbstract = updateInfoResource.isAbstract();
5028 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
5029 log.debug("Resource abstract is automatically set and cannot be updated");
5032 Boolean currentHighestVersion = currentResource.isHighestVersion();
5033 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
5035 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
5036 log.debug("Resource highest version is automatically set and cannot be updated");
5039 String currentUuid = currentResource.getUUID();
5040 String updatedUuid = updateInfoResource.getUUID();
5042 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
5043 log.debug("Resource UUID is automatically set and cannot be updated");
5046 log.debug("Resource Type cannot be updated");
5047 String currentInvariantUuid = currentResource.getInvariantUUID();
5048 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
5050 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5051 log.debug("Resource invariant UUID is automatically set and cannot be updated");
5052 updateInfoResource.setInvariantUUID(currentInvariantUuid);
5056 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
5058 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5059 log.debug("validate resource name before update");
5060 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
5061 log.debug("validate description before update");
5062 componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
5063 log.debug("validate icon before update");
5064 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5065 log.debug("validate tags before update");
5066 componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
5067 log.debug("validate vendor name before update");
5068 validateVendorName(null, updateInfoResource, null);
5069 log.debug("validate resource vendor model number before update");
5070 validateResourceVendorModelNumber(currentResource, updateInfoResource);
5071 log.debug("validate vendor release before update");
5072 validateVendorReleaseName(null, updateInfoResource, null);
5073 log.debug("validate contact info before update");
5074 componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
5075 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
5076 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5077 log.debug("validate category before update");
5078 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5081 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5082 String resourceNameUpdated = updateInfoResource.getName();
5083 String resourceNameCurrent = currentResource.getName();
5084 if (resourceNameCurrent.equals(resourceNameUpdated)) {
5087 // In case of CVFC type we should support the case of old VF with CVFC
5088 // instances that were created without the "Cvfc" suffix
5089 return currentResource.getResourceType() == ResourceTypeEnum.CVFC
5090 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5093 private String addCvfcSuffixToResourceName(String resourceName) {
5094 return resourceName + "Cvfc";
5097 private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
5099 String resourceNameUpdated = updateInfoResource.getName();
5100 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5101 if (isNested || !hasBeenCertified) {
5102 componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
5103 validateResourceNameUniqueness(updateInfoResource);
5104 currentResource.setName(resourceNameUpdated);
5105 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5106 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5109 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5110 resourceNameUpdated);
5111 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5116 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5117 String iconUpdated = updateInfoResource.getIcon();
5118 String iconCurrent = currentResource.getIcon();
5119 if (!iconCurrent.equals(iconUpdated)) {
5120 if (!hasBeenCertified) {
5121 componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
5123 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5124 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5129 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
5130 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5131 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5132 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5133 validateResourceVendorModelNumber(null, updateInfoResource, null);
5137 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5138 boolean hasBeenCertified, boolean inTransaction) {
5139 validateCategory(null, updateInfoResource, null, inTransaction);
5140 if (hasBeenCertified) {
5141 CategoryDefinition currentCategory = currentResource.getCategories()
5143 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
5145 CategoryDefinition updateCategory = updateInfoResource.getCategories()
5147 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
5149 if (!currentCategory.getName()
5150 .equals(updateCategory.getName())
5151 || !currentSubCategory.getName()
5152 .equals(updtaeSubCategory.getName())) {
5153 log.info("Category {} cannot be updated once the resource has been certified once.",
5154 currentResource.getCategories());
5155 ResponseFormat errorResponse = componentsUtils
5156 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5157 return Either.right(errorResponse);
5160 return Either.left(true);
5163 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5164 Resource updateInfoResource, boolean hasBeenCertified) {
5166 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5167 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5168 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5169 || updatedDerivedFrom.isEmpty()) {
5170 log.trace("Update normative types");
5171 return Either.left(true);
5174 String derivedFromCurrent = currentDerivedFrom.get(0);
5175 String derivedFromUpdated = updatedDerivedFrom.get(0);
5177 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5178 if (!hasBeenCertified) {
5179 validateDerivedFromExist(null, updateInfoResource, null);
5181 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5182 currentResource, updateInfoResource, null);
5184 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5186 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5187 return validateDerivedFromExtending;
5191 // For derived from, we must know whether it was actually changed,
5192 // otherwise we must do no action.
5193 // Due to changes it inflicts on data model (remove artifacts,
5194 // properties...), it's not like a flat field which can be
5195 // overwritten if not changed.
5196 // So we must indicate that derived from is not changed
5197 updateInfoResource.setDerivedFrom(null);
5199 return Either.left(true);
5202 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5203 Resource updateInfoResource, boolean hasBeenCertified) {
5205 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5206 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5207 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5208 || updatedDerivedFrom.isEmpty()) {
5209 log.trace("Update normative types");
5210 return Either.left(true);
5213 String derivedFromCurrent = currentDerivedFrom.get(0);
5214 String derivedFromUpdated = updatedDerivedFrom.get(0);
5216 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5217 if (!hasBeenCertified) {
5218 validateDerivedFromExist(null, updateInfoResource, null);
5220 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5221 currentResource, updateInfoResource, null);
5223 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5225 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5226 return validateDerivedFromExtending;
5230 return Either.left(true);
5233 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5234 if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
5238 String templateName = resource.getDerivedFrom()
5240 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5241 .validateToscaResourceNameExists(templateName);
5242 if (dataModelResponse.isRight()) {
5243 StorageOperationStatus storageStatus = dataModelResponse.right()
5245 BeEcompErrorManager.getInstance()
5246 .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5247 log.debug("request to data model failed with error: {}", storageStatus);
5248 ResponseFormat responseFormat = componentsUtils
5249 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5250 log.trace("audit before sending response");
5251 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5252 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
5253 } else if (!dataModelResponse.left()
5255 log.info("resource template with name: {}, does not exists", templateName);
5256 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5257 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5258 throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5262 // Tal G for extending inheritance US815447
5263 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5264 Resource updateInfoResource, AuditingActionEnum actionEnum) {
5265 String currentTemplateName = currentResource.getDerivedFrom()
5267 String updatedTemplateName = updateInfoResource.getDerivedFrom()
5270 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5271 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5272 if (dataModelResponse.isRight()) {
5273 StorageOperationStatus storageStatus = dataModelResponse.right()
5275 BeEcompErrorManager.getInstance()
5276 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5277 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5278 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5279 log.trace("audit before sending response");
5280 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5281 return Either.right(responseFormat);
5284 if (!dataModelResponse.left()
5286 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5287 currentTemplateName);
5288 ResponseFormat responseFormat = componentsUtils
5289 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5290 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5292 return Either.right(responseFormat);
5295 return Either.left(true);
5298 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5299 log.debug("validate resource derivedFrom field");
5300 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
5302 || (resource.getDerivedFrom()
5304 || (resource.getDerivedFrom()
5308 log.info("derived from (template) field is missing for the resource");
5309 ResponseFormat responseFormat = componentsUtils
5310 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5311 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5313 throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5317 private void validateResourceNameUniqueness(Resource resource) {
5319 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5320 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5321 resource.getComponentType());
5322 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
5324 log.debug("resource with name: {}, already exists", resource.getName());
5325 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
5326 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5327 } else if (resourceOperationResponse.isRight()) {
5328 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5329 throw new StorageException(resourceOperationResponse.right()
5334 private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5336 List<CategoryDefinition> categories = resource.getCategories();
5337 if (CollectionUtils.isEmpty(categories)) {
5338 log.debug(CATEGORY_IS_EMPTY);
5339 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5340 ComponentTypeEnum.RESOURCE.getValue());
5341 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5342 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5343 ComponentTypeEnum.RESOURCE.getValue());
5345 if (categories.size() > 1) {
5346 log.debug("Must be only one category for resource");
5347 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
5348 ComponentTypeEnum.RESOURCE.getValue());
5350 CategoryDefinition category = categories.get(0);
5351 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5352 if (CollectionUtils.isEmpty(subcategories)) {
5353 log.debug("Missinig subcategory for resource");
5354 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5356 if (subcategories.size() > 1) {
5357 log.debug("Must be only one sub category for resource");
5358 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5361 SubCategoryDefinition subcategory = subcategories.get(0);
5363 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5364 log.debug(CATEGORY_IS_EMPTY);
5365 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5366 ComponentTypeEnum.RESOURCE.getValue());
5367 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5368 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5369 ComponentTypeEnum.RESOURCE.getValue());
5371 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5372 log.debug(CATEGORY_IS_EMPTY);
5373 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5374 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5375 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5376 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
5377 ComponentTypeEnum.RESOURCE.getValue());
5380 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
5383 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
5384 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5385 ResponseFormat responseFormat;
5386 if (category != null && subcategory != null) {
5387 log.debug("validating resource category {} against valid categories list", category);
5388 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5389 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5390 if (categories.isRight()) {
5391 log.debug("failed to retrieve resource categories from JanusGraph");
5392 responseFormat = componentsUtils.getResponseFormat(categories.right()
5394 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5395 throw new ByActionStatusComponentException(categories.right()
5398 List<CategoryDefinition> categoryList = categories.left()
5400 Optional<CategoryDefinition> foundCategory = categoryList.stream()
5401 .filter(cat -> cat.getName()
5402 .equals(category.getName()))
5404 if (!foundCategory.isPresent()) {
5405 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5406 category, categoryList);
5407 failOnInvalidCategory(user, resource, actionEnum);
5409 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
5412 .filter(subcat -> subcat.getName()
5413 .equals(subcategory.getName()))
5415 if (!foundSubcategory.isPresent()) {
5417 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5418 subcategory, foundCategory.get()
5419 .getSubcategories());
5420 failOnInvalidCategory(user, resource, actionEnum);
5425 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
5426 ResponseFormat responseFormat;
5427 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5428 ComponentTypeEnum.RESOURCE.getValue());
5429 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5430 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5433 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
5434 String vendorRelease = resource.getVendorRelease();
5435 log.debug("validate vendor relese name");
5436 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5437 log.info("vendor relese name is missing.");
5438 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5439 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5440 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
5443 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
5446 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
5447 AuditingActionEnum actionEnum) {
5448 if (vendorRelease != null) {
5449 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
5450 log.info("vendor release exceds limit.");
5451 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5452 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5453 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5454 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
5455 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5458 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
5459 log.info("vendor release is not valid.");
5460 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
5461 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5462 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
5467 private void validateVendorName(User user, Resource resource,
5468 AuditingActionEnum actionEnum) {
5469 String vendorName = resource.getVendorName();
5470 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
5471 log.info("vendor name is missing.");
5472 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
5473 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5474 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
5476 validateVendorName(vendorName, user, resource, actionEnum);
5479 private void validateVendorName(String vendorName, User user, Resource resource,
5480 AuditingActionEnum actionEnum) {
5481 if (vendorName != null) {
5482 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
5483 log.info("vendor name exceds limit.");
5484 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5485 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5486 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5487 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5488 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5491 if (!ValidationUtils.validateVendorName(vendorName)) {
5492 log.info("vendor name is not valid.");
5493 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
5494 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5495 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME, vendorName);
5500 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
5501 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
5502 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
5503 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
5504 log.info("resource vendor model number exceeds limit.");
5505 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5506 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5507 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5508 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5509 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5510 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5512 // resource vendor model number is currently validated as vendor
5514 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
5515 log.info("resource vendor model number is not valid.");
5516 ResponseFormat errorResponse = componentsUtils
5517 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5518 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5519 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5525 private void validateCost(Resource resource) {
5526 String cost = resource.getCost();
5528 if (!ValidationUtils.validateCost(cost)) {
5529 log.debug("resource cost is invalid.");
5530 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5535 private void validateLicenseType(User user, Resource resource,
5536 AuditingActionEnum actionEnum) {
5537 log.debug("validate licenseType");
5538 String licenseType = resource.getLicenseType();
5539 if (licenseType != null) {
5540 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
5542 if (!licenseTypes.contains(licenseType)) {
5543 log.debug("License type {} isn't configured", licenseType);
5544 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5545 if (actionEnum != null) {
5546 // In update case, no audit is required
5547 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5549 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5554 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
5555 Resource updatedResource, String userId, boolean inTransaction) {
5556 if (updatedResource.getDerivedFrom() != null) {
5557 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
5558 log.debug("1. Removing interface artifacts from graph");
5559 // Remove all interface artifacts of resource
5560 String resourceId = updatedResource.getUniqueId();
5561 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
5563 if (interfaces != null) {
5564 Collection<InterfaceDefinition> values = interfaces.values();
5565 for (InterfaceDefinition interfaceDefinition : values) {
5566 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
5568 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
5569 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
5570 if (operations != null) {
5571 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
5572 Operation operation = operationEntry.getValue();
5573 ArtifactDefinition implementation = operation.getImplementationArtifact();
5574 if (implementation != null) {
5575 String uniqueId = implementation.getUniqueId();
5576 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
5577 uniqueId, operationEntry.getKey(), interfaceType);
5578 // only thing that transacts and locks here
5579 Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface =
5580 artifactsBusinessLogic.deleteArtifactByInterface(resourceId, userId, uniqueId, true);
5581 if (deleteArtifactByInterface.isRight()) {
5582 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
5583 if (!inTransaction) {
5584 janusGraphDao.rollback();
5586 return Either.right(deleteArtifactByInterface.right()
5590 log.trace("No implementation found for operation {} - nothing to delete",
5591 operationEntry.getKey());
5595 log.trace("No operations found for interface type {}", interfaceType);
5599 log.debug("2. Removing properties");
5600 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
5601 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
5603 if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
5604 log.debug("Failed to remove all properties of resource");
5605 if (!inTransaction) {
5606 janusGraphDao.rollback();
5608 return Either.right(componentsUtils
5609 .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
5614 log.debug("Derived from wasn't changed during update");
5617 if (inTransaction) {
5618 return Either.left(true);
5620 janusGraphDao.commit();
5621 return Either.left(true);
5625 /**** Auditing *******************/
5627 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
5628 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
5629 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
5631 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
5633 return webApplicationContext.getBean(class1);
5636 public ICapabilityTypeOperation getCapabilityTypeOperation() {
5637 return capabilityTypeOperation;
5641 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
5642 this.capabilityTypeOperation = capabilityTypeOperation;
5645 public Boolean validatePropertiesDefaultValues(Resource resource) {
5646 log.debug("validate resource properties default values");
5647 List<PropertyDefinition> properties = resource.getProperties();
5648 if (properties != null) {
5649 iterateOverProperties(properties);
5654 public void iterateOverProperties(List<PropertyDefinition> properties) {
5656 String innerType = null;
5657 for (PropertyDefinition property : properties) {
5658 if (!propertyOperation.isPropertyTypeValid(property)) {
5659 log.info("Invalid type for property {}", property);
5660 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
5661 property.getType(), property.getName());
5664 Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
5665 type = property.getType();
5667 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5668 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
5669 if (responseFormat != null) {
5673 validateDefaultPropertyValue(property, allDataTypes, type, innerType);
5677 private void validateDefaultPropertyValue(PropertyDefinition property,
5678 Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
5679 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
5680 log.info("Invalid default value for property {}", property);
5681 ResponseFormat responseFormat;
5682 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5683 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
5684 property.getName(), type, innerType, property.getDefaultValue());
5686 throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
5687 property.getName(), type, property.getDefaultValue());
5691 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
5692 Map<String, DataTypeDefinition> allDataTypes) {
5693 ResponseFormat responseFormat = null;
5694 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
5696 innerType = propertyInnerTypeValid.getLeft();
5697 if (!propertyInnerTypeValid.getRight()
5699 log.info("Invalid inner type for property {}", property);
5700 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
5701 property.getName());
5703 return responseFormat;
5707 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
5708 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
5712 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
5713 return componentInstanceBusinessLogic;
5716 private String getComponentTypeForResponse(Component component) {
5717 String componentTypeForResponse = "SERVICE";
5718 if (component instanceof Resource) {
5719 componentTypeForResponse = ((Resource) component).getResourceType()
5722 return componentTypeForResponse;
5725 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
5728 validateUserExists(user);
5730 // get resource from csar uuid
5731 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
5732 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
5733 if (either.isRight()) {
5734 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
5736 return Either.right(resp);
5739 return Either.left(either.left()
5744 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5745 String componentId, String userId) {
5749 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
5750 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5751 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5753 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5754 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
5755 defaultCapabilities, validCapabilitiesMap));
5756 return validCapabilitiesMap;
5759 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
5760 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5761 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
5762 String capabilityType = capabilities.get(0)
5764 if (defaultCapabilities.containsKey(capabilityType)) {
5765 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5766 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5767 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5768 validCapabilityList.add(defaultCapability);
5769 validCapabilitiesMap.put(key, validCapabilityList);
5771 throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
5775 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
5776 CapabilityDefinition defaultCapability) {
5777 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
5778 .getProperties())) {
5779 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5780 defaultCapability.getName(), resourceId);
5781 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
5782 defaultCapability.getName());
5783 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
5784 } else if (isNotEmpty(capabilities.get(0)
5785 .getProperties())) {
5786 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5790 private CapabilityDefinition getCapability(String resourceId,
5791 Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5792 CapabilityDefinition defaultCapability;
5793 if (isNotEmpty(defaultCapabilities.get(capabilityType)
5795 .getProperties())) {
5796 defaultCapability = defaultCapabilities.get(capabilityType)
5799 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5800 .getToscaFullElement(resourceId);
5801 if (getFullComponentRes.isRight()) {
5802 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
5804 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
5806 defaultCapability = getFullComponentRes.left()
5809 .get(capabilityType)
5812 return defaultCapability;
5815 private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
5816 UploadCapInfo uploadedCapability) {
5817 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5818 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
5820 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5821 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5822 for (UploadPropInfo property : uploadedProperties) {
5823 String propertyName = property.getName()
5825 String propertyType = property.getType();
5826 ComponentInstanceProperty validProperty;
5827 if (defaultProperties.containsKey(propertyName)
5828 && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5829 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
5831 validProperty = new ComponentInstanceProperty();
5832 validProperty.setName(propertyName);
5833 if (property.getValue() != null) {
5834 validProperty.setValue(property.getValue()
5837 validProperty.setDescription(property.getDescription());
5838 validProperty.setPassword(property.isPassword());
5839 validProperties.add(validProperty);
5841 defaultCapability.setProperties(validProperties);
5844 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
5845 String propertyType) {
5846 return propertyType != null && !defaultProperties.get(propertyName)
5848 .equals(propertyType);
5851 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5852 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5853 Resource resource, User user) {
5855 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5856 ArtifactOperationEnum.class);
5857 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5858 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5859 .left(nodeTypeArtifactsToHandle);
5861 // add all found Csar artifacts to list to upload
5862 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5863 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5864 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5865 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5866 ArtifactDefinition foundArtifact;
5868 if (!existingArtifactsToHandle.isEmpty()) {
5869 foundArtifact = existingArtifactsToHandle.stream()
5870 .filter(a -> a.getArtifactName()
5871 .equals(currNewArtifact.getArtifactName()))
5874 if (foundArtifact != null) {
5875 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
5876 if (!foundArtifact.getArtifactChecksum()
5877 .equals(currNewArtifact.getArtifactChecksum())) {
5878 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5879 // if current artifact already exists, but has
5880 // different content, add him to the list to
5882 artifactsToUpdate.add(currNewArtifact);
5884 // remove found artifact from the list of existing
5885 // artifacts to handle, because it was already
5887 existingArtifactsToHandle.remove(foundArtifact);
5888 // and remove found artifact from the list to
5889 // upload, because it should either be updated or be
5891 artifactsToUpload.remove(currNewArtifact);
5893 log.debug("Can't upload two artifact with the same name {}.",
5894 currNewArtifact.getArtifactName());
5895 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
5896 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5897 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
5898 foundArtifact.getArtifactType());
5899 AuditingActionEnum auditingAction = artifactsBusinessLogic
5900 .detectAuditingType(new ArtifactOperationInfo(false, false,
5901 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5902 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5903 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5904 resource.getComponentType(), null);
5905 responseWrapper.setInnerElement(responseFormat);
5911 if (responseWrapper.isEmpty()) {
5912 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5913 if (currArtifact.getIsFromCsar()) {
5914 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5915 currArtifact.getArtifactType(),
5916 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5917 currArtifact.getIsFromCsar()));
5919 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5920 currArtifact.getArtifactType(),
5921 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5922 currArtifact.getIsFromCsar()));
5927 if (responseWrapper.isEmpty()) {
5928 if (!artifactsToUpload.isEmpty()) {
5929 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5931 if (!artifactsToUpdate.isEmpty()) {
5932 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5934 if (!artifactsToDelete.isEmpty()) {
5935 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5938 if (!responseWrapper.isEmpty()) {
5939 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5941 } catch (Exception e) {
5942 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5943 responseWrapper.setInnerElement(responseFormat);
5944 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5946 return nodeTypeArtifactsToHandleRes;
5949 ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
5950 final String vfResourceName,
5951 final String nodeTypeFullName) {
5953 String actualVfName;
5954 if (ResourceTypeEnum.CVFC.name()
5955 .equals(nodeResourceType)) {
5956 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5957 actualType = ResourceTypeEnum.VFC.name();
5959 actualVfName = vfResourceName;
5960 actualType = nodeResourceType;
5962 String nameWithouNamespacePrefix;
5964 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
5965 log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
5966 + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName,
5967 nodeTypeFullName, actualType, vfResourceName);
5968 final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
5970 if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
5971 nameWithouNamespacePrefix = nodeTypeFullName;
5973 nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
5975 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5977 if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
5978 actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
5980 actualName = "." + nameWithouNamespacePrefix;
5983 if (actualName.startsWith(Constants.ABSTRACT)) {
5984 toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
5985 .append(ValidationUtils.convertToSystemName(actualVfName));
5987 toscaResourceName.append(actualType.toLowerCase()).append('.')
5988 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5990 final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5991 final String[] actualNames = actualName.split("\\.");
5992 if (actualNames.length < 3) {
5993 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5994 previousToscaResourceName.append(actualName).toString());
5996 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5997 previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
5998 .toLowerCase()).toString());
5999 } catch (final Exception e) {
6000 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
6001 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
6006 * Extracts a Node Type Name prefix from the given Node Type Name.
6008 * @param fullName Node Type Name
6009 * @return Node Type Name Prefix
6011 private String getNodeTypeNamePrefix(final String fullName) {
6012 String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
6013 final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
6014 log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
6015 final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
6016 if (validNameSpace.isPresent()) {
6017 tempPrefix = validNameSpace.get();
6019 log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
6024 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
6025 List<String> dataParamsToReturn) {
6027 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
6028 Either<Resource, StorageOperationStatus> resourceResultEither =
6029 toscaOperationFacade.getToscaElement(resourceId,
6032 if (resourceResultEither.isRight()) {
6033 if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
6034 log.debug("Failed to found resource with id {} ", resourceId);
6036 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
6039 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
6040 return Either.right(componentsUtils
6041 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
6045 Resource resource = resourceResultEither.left().value();
6046 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
6047 ListUtils.emptyIfNull(resource.getInputs())
6048 .forEach(input -> input.setConstraints(setInputConstraint(input)));
6051 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
6052 dataParamsToReturn);
6053 return Either.left(dataTransfer);
6057 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
6058 Resource resource = (Resource) clonedComponent;
6059 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
6060 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
6061 .shouldUpgradeToLatestDerived(resource);
6062 if (shouldUpgradeToLatestDerived.isRight()) {
6063 return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
6066 return Either.left(shouldUpgradeToLatestDerived.left()
6069 return super.shouldUpgradeToLatestDerived(clonedComponent);