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.ImportUtils.ResultStatusEnum;
66 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
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.components.ResourceMetadataDataDefinition;
97 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
98 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
99 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
100 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
101 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
102 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
103 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
104 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
105 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
106 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
107 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
108 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
109 import org.openecomp.sdc.be.impl.ComponentsUtils;
110 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
111 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
112 import org.openecomp.sdc.be.model.ArtifactDefinition;
113 import org.openecomp.sdc.be.model.AttributeDefinition;
114 import org.openecomp.sdc.be.model.CapabilityDefinition;
115 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
116 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
117 import org.openecomp.sdc.be.model.Component;
118 import org.openecomp.sdc.be.model.ComponentInstance;
119 import org.openecomp.sdc.be.model.ComponentInstanceInput;
120 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
121 import org.openecomp.sdc.be.model.ComponentParametersView;
122 import org.openecomp.sdc.be.model.DataTypeDefinition;
123 import org.openecomp.sdc.be.model.GroupDefinition;
124 import org.openecomp.sdc.be.model.InputDefinition;
125 import org.openecomp.sdc.be.model.InterfaceDefinition;
126 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
127 import org.openecomp.sdc.be.model.LifecycleStateEnum;
128 import org.openecomp.sdc.be.model.NodeTypeInfo;
129 import org.openecomp.sdc.be.model.Operation;
130 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
131 import org.openecomp.sdc.be.model.PolicyDefinition;
132 import org.openecomp.sdc.be.model.PropertyDefinition;
133 import org.openecomp.sdc.be.model.RelationshipImpl;
134 import org.openecomp.sdc.be.model.RelationshipInfo;
135 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
136 import org.openecomp.sdc.be.model.RequirementDefinition;
137 import org.openecomp.sdc.be.model.Resource;
138 import org.openecomp.sdc.be.model.UploadArtifactInfo;
139 import org.openecomp.sdc.be.model.UploadCapInfo;
140 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
141 import org.openecomp.sdc.be.model.UploadInfo;
142 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
143 import org.openecomp.sdc.be.model.UploadPropInfo;
144 import org.openecomp.sdc.be.model.UploadReqInfo;
145 import org.openecomp.sdc.be.model.UploadResourceInfo;
146 import org.openecomp.sdc.be.model.User;
147 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
148 import org.openecomp.sdc.be.model.category.CategoryDefinition;
149 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
150 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
151 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
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 private 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());
210 private IInterfaceLifecycleOperation interfaceTypeOperation;
211 private LifecycleBusinessLogic lifecycleBusinessLogic;
213 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
214 private final ResourceImportManager resourceImportManager;
215 private final InputsBusinessLogic inputsBusinessLogic;
216 private final OutputsBusinessLogic outputsBusinessLogic;
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(final IElementOperation elementDao,
228 final IGroupOperation groupOperation,
229 final IGroupInstanceOperation groupInstanceOperation,
230 final IGroupTypeOperation groupTypeOperation,
231 final GroupBusinessLogic groupBusinessLogic,
232 final InterfaceOperation interfaceOperation,
233 final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
234 final ArtifactsBusinessLogic artifactsBusinessLogic,
235 final ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
236 final @Lazy ResourceImportManager resourceImportManager,
237 final InputsBusinessLogic inputsBusinessLogic,
238 final OutputsBusinessLogic outputsBusinessLogic,
239 final CompositionBusinessLogic compositionBusinessLogic,
240 final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
241 final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
242 final MergeInstanceUtils mergeInstanceUtils,
243 final UiComponentDataConverter uiComponentDataConverter,
244 final CsarBusinessLogic csarBusinessLogic,
245 final ArtifactsOperations artifactToscaOperation,
246 final PropertyBusinessLogic propertyBusinessLogic,
247 final ComponentContactIdValidator componentContactIdValidator,
248 final ComponentNameValidator componentNameValidator,
249 final ComponentTagsValidator componentTagsValidator,
250 final ComponentValidator componentValidator,
251 final ComponentIconValidator componentIconValidator,
252 final ComponentProjectCodeValidator componentProjectCodeValidator,
253 final ComponentDescriptionValidator componentDescriptionValidator,
254 final PolicyBusinessLogic policyBusinessLogic) {
255 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
256 interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator,
257 componentNameValidator, componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
258 componentDescriptionValidator);
259 this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
260 this.resourceImportManager = resourceImportManager;
261 this.inputsBusinessLogic = inputsBusinessLogic;
262 this.outputsBusinessLogic = outputsBusinessLogic;
263 this.compositionBusinessLogic = compositionBusinessLogic;
264 this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
265 this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
266 this.mergeInstanceUtils = mergeInstanceUtils;
267 this.uiComponentDataConverter = uiComponentDataConverter;
268 this.csarBusinessLogic = csarBusinessLogic;
269 this.propertyBusinessLogic = propertyBusinessLogic;
270 this.policyBusinessLogic = policyBusinessLogic;
274 private ICapabilityTypeOperation capabilityTypeOperation;
277 private TopologyComparator topologyComparator;
280 private ComponentValidator componentValidator;
283 private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
286 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
288 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
289 return lifecycleBusinessLogic;
293 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
294 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
298 protected void setComponentValidator(ComponentValidator componentValidator) {
299 this.componentValidator = componentValidator;
302 public IElementOperation getElementDao() {
306 public void setElementDao(IElementOperation elementDao) {
307 this.elementDao = elementDao;
310 public UserBusinessLogic getUserAdmin() {
311 return this.userAdmin;
316 public void setUserAdmin(UserBusinessLogic userAdmin) {
317 this.userAdmin = userAdmin;
320 public ComponentsUtils getComponentsUtils() {
321 return this.componentsUtils;
326 public void setComponentsUtils(ComponentsUtils componentsUtils) {
327 this.componentsUtils = componentsUtils;
330 public ArtifactsBusinessLogic getArtifactsManager() {
331 return artifactsBusinessLogic;
334 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
335 this.artifactsBusinessLogic = artifactsManager;
338 public ApplicationDataTypeCache getApplicationDataTypeCache() {
339 return applicationDataTypeCache;
344 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
345 this.applicationDataTypeCache = applicationDataTypeCache;
349 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
350 this.interfaceTypeOperation = interfaceTypeOperation;
354 * the method returns a list of all the resources that are certified, the
355 * returned resources are only abstract or only none abstract according to
363 public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter,
365 User user = validateUserExists(userId);
366 Boolean isHighest = null;
367 switch (highestFilter) {
373 case NON_HIGHEST_ONLY:
379 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
380 .getAllCertifiedResources(getAbstract, isHighest);
382 if (getResponse.isRight()) {
383 throw new StorageException(getResponse.right()
387 return getResponse.left()
391 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
392 ResourceTypeEnum resourceTypeEnum, String userId) {
394 validateUserExists(userId);
396 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
397 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
399 janusGraphDao.commit();
401 if (dataModelResponse.isLeft()) {
402 Map<String, Boolean> result = new HashMap<>();
403 result.put("isValid", dataModelResponse.left()
405 log.debug("validation was successfully performed.");
406 return Either.left(result);
409 ResponseFormat responseFormat = componentsUtils
410 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
413 return Either.right(responseFormat);
416 public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user,
417 Map<String, byte[]> csarUIPayload, String payloadName) {
418 validateResourceBeforeCreate(resource, user, false);
419 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
420 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId());
421 if (StringUtils.isNotEmpty(csarUUID)) {
422 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
423 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
425 Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
426 return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left()
427 .map(r -> (Resource) r)
432 final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
433 return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left()
434 .map(r -> (Resource) r)
439 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
440 String payloadName, String resourceUniqueId) {
441 String csarUUID = payloadName;
442 String csarVersion = null;
443 Resource updatedResource = null;
444 if (payloadName == null) {
445 csarUUID = resource.getCsarUUID();
446 csarVersion = resource.getCsarVersion();
448 if (csarUUID != null && !csarUUID.isEmpty()) {
449 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
450 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
451 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
452 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
453 overrideImmutableMetadata(oldResource, resource);
455 validateResourceBeforeCreate(resource, user, false);
456 String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null;
457 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
459 // (on boarding flow): If the update includes same csarUUID and
460 // same csarVersion as already in the VF - no need to import the
461 // csar (do only metadata changes if there are).
462 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
463 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
465 updatedResource = updateResourceFromCsar(oldResource, resource, user,
466 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
469 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
470 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
472 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
473 throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
475 return updatedResource;
478 private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
479 // (on boarding flow): If the update includes a csarUUID: verify this
480 // csarUUID is not in use by another VF, If it is - use same error as
482 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
483 // select another or update the existing VF." %1 - csarUUID, %2 - VF
485 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
486 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
487 if (resourceLinkedToCsarRes.isRight()) {
488 if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
489 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
490 resource.getSystemName());
491 throw new StorageException(resourceLinkedToCsarRes.right()
494 } else if (!resourceLinkedToCsarRes.left()
497 .equals(oldResource.getUniqueId())
498 && !resourceLinkedToCsarRes.left()
501 .equals(oldResource.getName())) {
502 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
503 resourceLinkedToCsarRes.left()
506 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
507 throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left()
513 private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID,
514 String resourceUniqueId, User user) {
515 // (on boarding flow): If the update includes csarUUID which is
516 // different from the csarUUID of the VF - fail with
517 // error: "Error: Resource %1 cannot be updated using since it is linked
518 // to a different VSP" %1 - VF name
519 String oldCsarUUID = oldResource.getCsarUUID();
520 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
522 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
523 resourceUniqueId, csarUUID, oldCsarUUID);
524 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
525 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
526 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
527 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID,
532 private Resource getResourceByUniqueId(String resourceUniqueId) {
533 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade
534 .getToscaFullElement(resourceUniqueId);
535 if (oldResourceRes.isRight()) {
536 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
537 oldResourceRes.right()
539 throw new StorageException(oldResourceRes.right()
542 return oldResourceRes.left()
546 private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
547 resource.setName(oldResource.getName());
548 resource.setIcon(oldResource.getIcon());
549 resource.setTags(oldResource.getTags());
550 resource.setCategories(oldResource.getCategories());
551 resource.setDerivedFrom(oldResource.getDerivedFrom());
554 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user,
555 AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload,
557 Resource updatedResource = null;
558 validateLifecycleState(oldResource, user);
559 String lockedResourceId = oldResource.getUniqueId();
560 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
561 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
562 lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
564 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
566 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
567 nodeTypesInfo, csarInfo, oldResource);
568 if (findNodeTypesArtifactsToHandleRes.isRight()) {
569 log.debug("failed to find node types for update with artifacts during import csar {}. ",
570 csarInfo.getCsarUUID());
571 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right()
574 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
578 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts,
579 csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo,
580 nodeTypesArtifactsToHandle, null, false);
582 } catch (ComponentException | StorageException e) {
583 rollback(inTransaction, newResource, createdArtifacts, null);
587 janusGraphDao.commit();
588 log.debug("unlock resource {}", lockedResourceId);
589 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
591 return updatedResource;
595 private void validateLifecycleState(Resource oldResource, User user) {
596 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState()
597 && !oldResource.getLastUpdaterUserId()
598 .equals(user.getUserId())) {
600 "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
601 oldResource.getLastUpdaterUserId(), user.getUserId());
602 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
606 private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
607 List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
608 Map<String, NodeTypeInfo> nodeTypesInfo,
609 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
610 String nodeName, boolean isNested) {
611 boolean inTransaction = true;
612 boolean shouldLock = false;
613 Resource preparedResource = null;
614 ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
616 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName,
617 nodeTypesInfo, csarInfo, nodeName, oldResource);
618 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
619 if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
620 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
622 preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(),
623 inTransaction, shouldLock, isNested).left;
624 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
625 handleResourceGenericType(preparedResource);
626 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle,
627 createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
628 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
629 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
630 preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
631 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames);
632 } catch (ComponentException e) {
633 ResponseFormat responseFormat = e.getResponseFormat() == null
634 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
635 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
637 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
638 preparedResource == null ? oldResource : preparedResource, actionEnum);
640 } catch (StorageException e) {
641 ResponseFormat responseFormat = componentsUtils
642 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
643 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
645 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
646 preparedResource == null ? oldResource : preparedResource, actionEnum);
649 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
650 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
651 preparedResource.getSystemName());
652 if (validateUpdateVfGroupNamesRes.isRight()) {
654 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right()
657 // add groups to newResource
658 Map<String, GroupDefinition> groups;
660 if (!validateUpdateVfGroupNamesRes.left()
663 groups = validateUpdateVfGroupNamesRes.left()
666 groups = uploadComponentInstanceInfoMap.getGroups();
668 handleGroupsProperties(preparedResource, groups);
669 Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
671 preparedResource = updateGroupsOnResource(preparedResource, groups);
673 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
674 nodeTypesArtifactsToHandle);
676 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE,
677 createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts,
678 inTransaction, shouldLock);
679 if (updateArtifactsEither.isRight()) {
680 log.debug("failed to update artifacts {}", updateArtifactsEither.right()
682 throw new ByResponseFormatComponentException(updateArtifactsEither.right()
685 preparedResource = getResourceWithGroups(updateArtifactsEither.left()
689 updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
690 updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
692 final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
693 preparedResource = getResourceWithGroups(preparedResourceId);
695 updateVolumeGroup(preparedResource);
697 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
698 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
699 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
701 throw new ByResponseFormatComponentException(responseFormat);
703 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
705 return preparedResource;
708 protected void updateVolumeGroup(Resource preparedResource) {
709 List<GroupDefinition> groups = preparedResource.safeGetGroups();
710 for (GroupDefinition group : groups) {
711 Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
712 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
713 List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
714 if (!volumePropList.isEmpty()) {
715 PropertyDataDefinition volumeProp = volumePropList.get(0);
716 if (volumeProp != null) {
717 boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
719 if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
720 volumeProp.setValue(String.valueOf(isVolumeGroup));
721 volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
729 private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
730 if (oldResource == null || preparedResource == null) {
731 log.debug("Failed to update groups name : oldResource or preparedResource is null");
732 } else if (CollectionUtils.isNotEmpty(oldResource.getGroups())
733 && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
734 Map<String, String> oldGroups = oldResource.getGroups()
736 .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
738 List<GroupDefinition> updatedGroups = preparedResource.getGroups()
740 .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
741 .equals(oldGroups.get(group.getInvariantName())))
744 if (CollectionUtils.isNotEmpty(updatedGroups)) {
745 if (isTopologyChanged) {
746 updatedGroups.stream().filter(group -> !group.isVspOriginated())
747 .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
749 updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
751 groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
756 private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource,
757 boolean isTopologyChanged) {
758 if (oldResource == null || preparedResource == null) {
759 log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
761 if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
762 Map<String, String> oldInstances = oldResource.getComponentInstances()
764 .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
765 List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
767 .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
768 .equals(oldInstances.get(i.getInvariantName())))
770 if (CollectionUtils.isNotEmpty(updatedInstances)) {
771 if (isTopologyChanged) {
772 updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
773 .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
775 updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
780 componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
781 null, preparedResource.getUniqueId(), csarInfo.getModifier()
783 preparedResource.getComponentInstances(), false);
787 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
788 List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
789 Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
790 boolean inTransaction, boolean shouldLock) {
792 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
793 Resource resource = preparedResource;
795 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
796 .getNodeTypesArtifactsToHandle();
797 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
798 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
799 && !nodeTypesArtifactsToHandle.get(nodeName)
801 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
802 preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
803 csarInfo.getModifier(), inTransaction, true);
804 if (handleNodeTypeArtifactsRes.isRight()) {
805 return Either.right(handleNodeTypeArtifactsRes.right()
810 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
811 csarInfo, createdArtifacts,
812 new ArtifactOperationInfo(false, false, operation), shouldLock,
814 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
815 if (createdCsarArtifactsEither.isRight()) {
816 return createdCsarArtifactsEither;
819 resource = createdCsarArtifactsEither.left()
822 return Either.left(resource);
825 private Resource handleResourceGenericType(Resource resource) {
826 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
827 if (resource.shouldGenerateInputs()) {
828 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
830 return genericResource;
833 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
834 final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
836 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
837 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
838 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
841 final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
842 .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
843 final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
844 nodeTypesInfo, oldResource.getName(), csarInfo);
845 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
846 oldResource.getName(), csarInfo.getCsarUUID());
847 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
848 nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
849 } catch (Exception e) {
850 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
851 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
852 log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
854 return nodeTypesArtifactsToHandleRes;
857 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
858 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
859 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
860 ImmutablePair<String, String> vfcToscaNames) {
862 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
863 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
864 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
866 if (!isEmpty(extractedVfcsArtifacts)) {
867 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
868 if (extractedVfcsArtifacts.containsKey(namespace)) {
869 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
871 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
872 } else if (curNodeType != null) {
873 // delete all artifacts if have not received artifacts from
875 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
876 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
877 // delete all informational artifacts
878 artifactsToDelete.addAll(curNodeType.getArtifacts()
881 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
883 // delete all deployment artifacts
884 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
886 if (!artifactsToDelete.isEmpty()) {
887 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
890 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
891 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
895 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
896 String previousVfcToscaName, StorageOperationStatus status) {
897 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
898 log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
900 ResponseFormat responseFormat = componentsUtils
901 .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
902 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
903 AuditingActionEnum.CREATE_RESOURCE);
904 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
905 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
906 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
908 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
913 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
914 List<ArtifactDefinition> extractedArtifacts) {
917 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
918 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
919 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
920 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
921 artifactsToDelete, collectExistingArtifacts(curNodeType));
922 return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
923 } catch (Exception e) {
924 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
925 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
929 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
930 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
931 List<ArtifactDefinition> artifactsToDelete) {
932 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
933 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
934 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
935 if (!artifactsToUpload.isEmpty()) {
936 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
938 if (!artifactsToUpdate.isEmpty()) {
939 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
941 if (!artifactsToDelete.isEmpty()) {
942 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
945 return nodeTypeArtifactsToHandle;
948 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
949 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
950 List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
951 if (!existingArtifacts.isEmpty()) {
952 extractedArtifacts.stream()
953 .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
954 artifactsToDelete.addAll(existingArtifacts.values());
958 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
959 List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
960 ArtifactDefinition currNewArtifact) {
961 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
963 .filter(a -> a.getArtifactName()
964 .equals(currNewArtifact.getArtifactName()))
966 if (foundArtifact.isPresent()) {
967 if (foundArtifact.get()
969 .equals(currNewArtifact.getArtifactType())) {
970 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
971 existingArtifacts.remove(foundArtifact.get()
972 .getArtifactLabel());
973 artifactsToUpload.remove(currNewArtifact);
975 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
976 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
977 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
983 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
984 ArtifactDefinition foundArtifact) {
985 if (!foundArtifact.getArtifactChecksum()
986 .equals(currNewArtifact.getArtifactChecksum())) {
987 foundArtifact.setPayload(currNewArtifact.getPayloadData());
988 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
989 foundArtifact.setArtifactChecksum(
990 GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
991 artifactsToUpdate.add(foundArtifact);
995 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
996 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
997 if (curNodeType == null) {
998 return existingArtifacts;
1000 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
1001 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
1003 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
1004 existingArtifacts.putAll(curNodeType.getArtifacts()
1007 .filter(e -> e.getValue()
1008 .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
1009 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
1011 return existingArtifacts;
1015 * Changes resource life cycle state to checked out
1019 * @param inTransaction
1022 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
1023 Either<Resource, ResponseFormat> checkoutResourceRes;
1025 if (!resource.getComponentMetadataDefinition()
1026 .getMetadataDataDefinition()
1028 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
1030 "************* Going to change life cycle state of resource {} to not certified checked out. ",
1031 resource.getName());
1032 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
1033 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1034 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1035 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
1036 inTransaction, true);
1037 if (checkoutRes.isRight()) {
1038 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
1039 resource.getComponentType()
1041 resource.getUniqueId(), checkoutRes.right()
1044 checkoutResourceRes = Either.right(checkoutRes.right()
1047 checkoutResourceRes = Either.left((Resource) checkoutRes.left()
1051 checkoutResourceRes = Either.left(resource);
1053 } catch (Exception e) {
1054 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1055 checkoutResourceRes = Either.right(responseFormat);
1056 log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
1059 return checkoutResourceRes;
1063 * Handles Artifacts of NodeType
1065 * @param nodeTypeResource
1066 * @param nodeTypeArtifactsToHandle
1068 * @param inTransaction
1071 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
1072 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1073 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
1074 List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
1075 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1076 Either<Resource, ResponseFormat> changeStateResponse;
1078 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1079 if (changeStateResponse.isRight()) {
1080 return Either.right(changeStateResponse.right()
1083 nodeTypeResource = changeStateResponse.left()
1086 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1087 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1088 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1090 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1091 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1092 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1093 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
1094 nodeTypeResource.getName());
1095 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1096 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
1097 createdArtifacts, new ArtifactOperationInfo(false,
1098 ignoreLifecycleState, curOperation),
1099 false, inTransaction);
1100 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1101 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1103 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1106 if (handleNodeTypeArtifactsRes == null) {
1107 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1109 } catch (Exception e) {
1110 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1111 handleNodeTypeArtifactsRes = Either.right(responseFormat);
1112 log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1114 return handleNodeTypeArtifactsRes;
1117 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
1118 final String vfResourceName,
1119 final CsarInfo csarInfo) {
1120 final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
1122 final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
1123 if (!nodes.isEmpty()) {
1124 final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
1125 while (nodesNameEntry.hasNext()) {
1126 final Entry<String, Object> nodeType = nodesNameEntry.next();
1127 final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
1128 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
1129 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
1132 for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
1133 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
1134 vfResourceName, cvfc.getType()));
1136 return vfcToscaNames;
1139 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1140 Map<String, Object> nodes = new HashMap<>();
1141 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
1142 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
1144 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
1148 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
1149 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1150 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
1151 if (eitherNodeTypes.isLeft()) {
1152 nodes.putAll(eitherNodeTypes.left()
1157 public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
1159 log.trace("************* created successfully from YAML, resource TOSCA ");
1160 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
1161 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
1162 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
1163 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
1164 nodeTypesInfo, csarInfo, resource);
1165 if (findNodeTypesArtifactsToHandleRes.isRight()) {
1166 log.debug("failed to find node types for update with artifacts during import csar {}. ",
1167 csarInfo.getCsarUUID());
1168 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1169 StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
1170 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
1172 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
1173 csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
1176 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
1177 vfResource.getToscaResourceName());
1178 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
1182 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1183 log.trace("validating resource before create");
1184 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
1185 // validate user role
1186 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
1187 // VF / PNF "derivedFrom" should be null (or ignored)
1188 if (ModelConverter.isAtomicComponent(resource)) {
1189 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1191 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1195 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
1196 // nodeTypesArtifactsToCreate, true, false, null
1197 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1198 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1199 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1200 boolean shouldLock, boolean inTransaction, String nodeName) {
1202 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
1203 Resource createdResource;
1205 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
1206 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
1207 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1209 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
1210 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1211 StatusCode.STARTED,"");
1212 createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1213 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
1214 csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1215 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
1216 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1217 StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
1218 } catch (ComponentException e) {
1219 ResponseFormat responseFormat = e.getResponseFormat() == null
1220 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
1221 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1222 AuditingActionEnum.IMPORT_RESOURCE);
1224 } catch (StorageException e) {
1225 ResponseFormat responseFormat = componentsUtils
1226 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1227 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1228 AuditingActionEnum.IMPORT_RESOURCE);
1231 return createdResource;
1235 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
1236 Map<String, Object> mappedToscaTemplate, boolean needLock,
1237 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1238 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1239 CsarInfo csarInfo) {
1241 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1242 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1243 if (toscaVersion.isRight()) {
1244 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1246 Map<String, Object> mapToConvert = new HashMap<>();
1247 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
1249 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1250 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1251 nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1252 return csarInfo.getCreatedNodes();
1255 private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1256 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1258 .orValue(HashMap::new);
1261 private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1262 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1263 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1264 CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1265 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
1267 Resource vfcCreated = null;
1268 while (nodesNameValueIter.hasNext()) {
1269 Entry<String, Object> nodeType = nodesNameValueIter.next();
1270 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1271 || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1273 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1274 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1275 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1276 nodeTypesInfo, csarInfo, nodeType.getKey());
1277 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1278 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1279 && !csarInfo.getCreatedNodesToscaResourceNames()
1280 .containsKey(nodeType.getKey())) {
1281 log.trace("************* Going to create node {}", nodeType.getKey());
1282 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
1283 nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
1284 nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1285 log.debug("************* Finished to create node {}", nodeType.getKey());
1287 vfcCreated = resourceCreated.getLeft();
1288 csarInfo.getCreatedNodesToscaResourceNames()
1289 .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1291 if (vfcCreated != null) {
1292 csarInfo.getCreatedNodes()
1293 .put(nodeType.getKey(), vfcCreated);
1295 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1299 private Resource handleNestedVfc(Resource resource,
1300 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1301 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1304 String yamlName = nodesInfo.get(nodeName)
1305 .getTemplateFileName();
1306 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
1307 .getMappedToscaTemplate();
1309 log.debug("************* Going to create node types from yaml {}", yamlName);
1310 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
1311 createdArtifacts, Collections.emptyMap(), csarInfo);
1312 log.debug("************* Finished to create node types from yaml {}", yamlName);
1314 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1315 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1316 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
1317 nodeName, yamlName);
1322 private Resource handleComplexVfc(final Resource resource,
1323 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
1324 nodesArtifactsToHandle,
1325 final List<ArtifactDefinition>
1326 createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1327 final String nodeName, final String yamlName) {
1329 Resource oldComplexVfc = null;
1330 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1331 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1332 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1333 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1334 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1335 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1337 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1338 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1339 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1340 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1341 } else if (oldComplexVfcRes.isLeft()) {
1342 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1343 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1344 oldComplexVfcRes.left().value(),
1345 newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1346 if (eitherValidation.isLeft()) {
1347 oldComplexVfc = oldComplexVfcRes.left().value();
1350 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
1351 yamlName, oldComplexVfc, newComplexVfc);
1352 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1353 final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1354 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1355 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1356 final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
1357 lifecycleChangeInfo, true, false, true);
1358 csarInfo.getCreatedNodes().put(nodeName, result);
1359 csarInfo.removeNodeFromQueue();
1363 private Resource handleComplexVfc(
1364 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1365 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1366 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1368 Resource handleComplexVfcRes;
1369 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
1370 .getMappedToscaTemplate();
1371 String yamlContent = new String(csarInfo.getCsar()
1373 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
1375 .collect(toMap(Entry::getKey, e -> e.getValue()
1376 .getUnmarkedCopy()));
1377 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1378 if (oldComplexVfc == null) {
1379 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1380 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1382 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1383 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1384 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1386 return handleComplexVfcRes;
1389 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1390 Map<String, NodeTypeInfo> nodesInfo) {
1392 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1393 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1394 csarInfo.addNodeToQueue(nodeName);
1395 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
1399 private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
1401 final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
1402 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1404 if(findTypes.length > 1){
1405 final String resourceType = findTypes[0];
1406 return nameWithouNamespacePrefix.substring(resourceType.length());
1408 return nameWithouNamespacePrefix;
1411 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
1412 final Entry<String, Object> nodeNameValue,
1414 final Map<String, Object> mapToConvert,
1415 final Resource resourceVf,
1416 final boolean needLock,
1417 final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1418 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1419 final boolean forceCertificationAllowed,
1420 final CsarInfo csarInfo,
1421 final boolean isNested) {
1423 final UploadResourceInfo resourceMetaData = fillResourceMetadata(
1424 yamlName, resourceVf, nodeNameValue.getKey(), user);
1426 final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1427 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1428 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1429 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1430 nodeNameValue.getKey(), isNested);
1433 private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
1434 final Map<String, Object> mapToConvert,
1435 final String nodeResourceType,
1436 final CsarInfo csarInfo) {
1437 // We need to create a Yaml from each node_types in order to create
1438 // resource from each node type using import normative flow.
1439 final DumperOptions options = new DumperOptions();
1440 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1441 final Yaml yaml = new Yaml(options);
1443 final Map<String, Object> node = new HashMap<>();
1444 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1445 .getLeft(), nodeNameValue.getValue());
1446 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1448 return yaml.dumpAsMap(mapToConvert);
1451 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1452 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1456 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
1457 UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1458 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1459 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1460 String nodeName, boolean isNested) {
1462 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1463 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1464 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1466 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1467 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1468 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1472 * Validates if a given node type name has a valid prefix.
1474 * @param nodeName node name from definition file
1475 * @param definedResourceNamespaceList is a list of all node type name prefix allowed
1476 * @return a valid node type name prefix if it`s found
1478 public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
1479 final List<String> definedResourceNamespaceList) {
1480 for (final String validNamespace : definedResourceNamespaceList) {
1481 if (nodeName.startsWith(validNamespace)) {
1482 return Optional.of(validNamespace);
1485 return Optional.empty();
1488 private List<String> getDefinedNodeTypeNamespaceList() {
1489 return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
1492 private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
1493 final String nodeName, final User user) {
1495 final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1497 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
1498 log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
1500 if (!nodeName.startsWith(nodeTypeNamePrefix)) {
1501 log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
1502 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1503 resourceMetaData.getName(), nodeName);
1506 final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
1507 final String namePrefix = nodeName.replace(actualName, "");
1508 String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
1509 log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
1510 resourceType, nodeName, actualName, nodeTypeNamePrefix);
1512 // if we import from csar, the node_type name can be
1513 // org.openecomp.resource.abstract.node_name - in this case we always
1515 if (resourceType.equals(Constants.ABSTRACT)) {
1516 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1519 if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
1520 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1524 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1525 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
1526 resourceType.toUpperCase(), ResourceTypeEnum.values());
1527 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1528 resourceMetaData.getName(), nodeName);
1532 resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
1534 // Setting type from name
1535 final String type = resourceType.toUpperCase();
1536 resourceMetaData.setResourceType(type);
1538 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1539 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1540 resourceMetaData.setContactId(user.getUserId());
1541 resourceMetaData.setVendorName(resourceVf.getVendorName());
1542 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1545 final List<String> tags = new ArrayList<>();
1546 tags.add(resourceMetaData.getName());
1547 resourceMetaData.setTags(tags);
1550 final CategoryDefinition category = new CategoryDefinition();
1551 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1552 final SubCategoryDefinition subCategory = new SubCategoryDefinition();
1553 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1554 category.addSubCategory(subCategory);
1555 final List<CategoryDefinition> categories = new ArrayList<>();
1556 categories.add(category);
1557 resourceMetaData.setCategories(categories);
1559 return resourceMetaData;
1562 private Resource buildComplexVfcMetadata(final Resource resourceVf,
1563 final CsarInfo csarInfo,
1564 final String nodeName,
1565 final Map<String, NodeTypeInfo> nodesInfo) {
1566 final Resource cvfc = new Resource();
1567 final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1568 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1569 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1570 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1571 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1572 cvfc.setAbstract(true);
1573 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1574 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1575 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1576 cvfc.setContactId(csarInfo.getModifier()
1578 cvfc.setCreatorUserId(csarInfo.getModifier()
1580 cvfc.setVendorName(resourceVf.getVendorName());
1581 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1582 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1583 cvfc.setToscaResourceName(buildNestedToscaResourceName(
1584 ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1585 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1587 final List<String> tags = new ArrayList<>();
1588 tags.add(cvfc.getName());
1591 final CategoryDefinition category = new CategoryDefinition();
1592 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1593 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1594 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1595 category.addSubCategory(subCategory);
1596 final List<CategoryDefinition> categories = new ArrayList<>();
1597 categories.add(category);
1598 cvfc.setCategories(categories);
1600 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1601 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1602 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1607 private String buildCvfcName(final String resourceVfName, final String nodeName) {
1609 String nameWithouNamespacePrefix =
1610 nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1611 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1612 String resourceType = findTypes[0];
1613 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1614 return addCvfcSuffixToResourceName(resourceName);
1617 private Resource createResourceAndRIsFromYaml(final String yamlName,
1619 final ParsedToscaYamlInfo parsedToscaYamlInfo,
1620 final AuditingActionEnum actionEnum,
1621 final boolean isNormative,
1622 final List<ArtifactDefinition> createdArtifacts,
1623 final String topologyTemplateYaml,
1624 final Map<String, NodeTypeInfo> nodeTypesInfo,
1625 final CsarInfo csarInfo,
1626 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1627 final boolean shouldLock,
1628 final boolean inTransaction,
1629 final String nodeName) {
1631 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1634 final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1636 if (lockResult.isRight()) {
1637 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1638 throw new ByResponseFormatComponentException(lockResult.right().value());
1640 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1643 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1644 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
1645 final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1646 resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
1647 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1648 log.trace("************* Going to add inputs from yaml {}", yamlName);
1649 if (resource.shouldGenerateInputs())
1650 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1652 final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1653 resource = createInputsOnResource(resource, inputs);
1654 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1655 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
1656 resource.getComponentMetadataForSupportLog(),
1657 StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
1658 if (resource.getResourceType() == ResourceTypeEnum.PNF) {
1659 log.trace("************* Adding generic properties to PNF");
1660 resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
1661 genericResource.getProperties());
1662 log.trace("************* Adding software information to PNF");
1663 softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
1664 log.trace("************* Removing non-mano software information file from PNF");
1665 if (csarInfo.getSoftwareInformationPath().isPresent() &&
1666 !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
1667 log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
1668 "catalog-be", "Could not remove the software information file.");
1672 final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1674 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1675 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName);
1676 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1677 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
1679 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1680 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
1681 resource.getComponentMetadataForSupportLog(),
1682 StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName);
1683 // validate update vf module group names
1684 final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1685 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1686 if (validateUpdateVfGroupNamesRes.isRight()) {
1687 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1688 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1690 // add groups to resource
1691 final Map<String, GroupDefinition> groups;
1692 log.trace("************* Going to add groups from yaml {}", yamlName);
1693 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
1694 StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
1695 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1696 groups = validateUpdateVfGroupNamesRes.left().value();
1698 groups = parsedToscaYamlInfo.getGroups();
1701 final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
1702 if (createGroupsOnResource.isRight()) {
1703 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1704 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1705 resource.getComponentMetadataForSupportLog(),
1706 StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
1707 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1709 resource = createGroupsOnResource.left().value();
1710 log.trace("************* Finished to add groups from yaml {}", yamlName);
1711 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1712 resource.getComponentMetadataForSupportLog(),
1713 StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
1714 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1715 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1716 resource.getComponentMetadataForSupportLog(),
1717 StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
1719 log.trace("************* Starting to add policies from yaml {}", yamlName);
1720 Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
1721 if (MapUtils.isNotEmpty(policies)) {
1722 resource = createPoliciesOnResource(resource, policies);
1724 log.trace("************* Finished to add policies from yaml {}", yamlName);
1726 final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
1727 new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
1729 final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
1730 ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
1731 nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1732 if (createArtifactsEither.isRight()) {
1733 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1734 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1735 resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
1736 createArtifactsEither.right().value());
1737 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1739 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1740 resource.getComponentMetadataForSupportLog(),
1741 StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
1742 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1743 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1744 ASDCKpiApi.countCreatedResourcesKPI();
1747 } catch (final BusinessLogicException e) {
1748 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
1749 "An error has occurred during resource and resource instance creation", e);
1750 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1751 throw new ByResponseFormatComponentException(e.getResponseFormat());
1752 } catch (final Exception e) {
1753 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
1754 "An error has occurred during resource and resource instance creation", e);
1755 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1756 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1758 if (!inTransaction) {
1759 janusGraphDao.commit();
1762 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1763 NodeTypeEnum.Resource);
1768 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1769 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1770 if (!inTransaction) {
1771 janusGraphDao.rollback();
1773 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1774 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1775 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
1776 resource.getName());
1780 private Resource getResourceWithGroups(String resourceId) {
1782 ComponentParametersView filter = new ComponentParametersView();
1783 filter.setIgnoreGroups(false);
1784 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
1786 if (updatedResource.isRight()) {
1787 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
1788 .value()), resourceId);
1790 return updatedResource.left()
1794 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1795 Map<String, GroupDefinition> groups) {
1796 if (groups != null && !groups.isEmpty()) {
1797 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1798 handleGroupsProperties(resource, groups);
1799 fillGroupsFinalFields(groupsAsList);
1800 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1801 groupsAsList, true);
1802 if (createGroups.isRight()) {
1803 return Either.right(createGroups.right()
1807 return Either.left(resource);
1810 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1811 List<InputDefinition> inputs = resource.getInputs();
1812 if (MapUtils.isNotEmpty(groups)) {
1815 .filter(g -> isNotEmpty(g.getProperties()))
1816 .flatMap(g -> g.getProperties()
1818 .forEach(p -> handleGetInputs(p, inputs));
1822 private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
1823 policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
1827 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1828 if (isNotEmpty(property.getGetInputValues())) {
1829 if (inputs == null || inputs.isEmpty()) {
1830 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1831 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1833 .map(GetInputValueDataDefinition::getInputName)
1837 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
1839 while (getInputValuesIter.hasNext()) {
1840 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1841 Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
1842 if (inputEither.isRight()) {
1843 throw inputEither.right().value();
1845 InputDefinition input = inputEither.left().value();
1846 getInput.setInputId(input.getUniqueId());
1847 if (getInput.getGetInputIndex() != null) {
1848 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1849 Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
1851 if (newInputEither.isRight()) {
1852 throw newInputEither.right().value();
1854 InputDefinition newInput = newInputEither.left().value();
1855 getInputIndex.setInputId(newInput.getUniqueId());
1857 getInputValuesIter.add(getInputIndex);
1864 static <T> Either<T, RuntimeException> rollbackWithEither(
1865 final JanusGraphDao janusGraphDao,
1866 final ActionStatus actionStatus,
1867 final String... params) {
1868 if (janusGraphDao != null)
1869 janusGraphDao.rollback();
1870 return Either.right(new ByActionStatusComponentException(actionStatus, params));
1873 <T> Either<T, RuntimeException> rollbackWithEither(
1874 final ActionStatus actionStatus,
1875 final String... params) {
1876 return rollbackWithEither(janusGraphDao, actionStatus, params);
1879 private Either<InputDefinition, RuntimeException> findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1881 final String inputName = getInput != null ? getInput.getInputName() : "";
1883 if(inputs == null || inputs.isEmpty()) {
1884 log.debug("#findInputByName - Inputs list is empty");
1885 return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
1887 Optional<InputDefinition> inputOpt = inputs.stream()
1888 .filter(p -> p.getName().equals(inputName))
1890 if (!inputOpt.isPresent()) {
1891 log.debug("#findInputByName - Failed to find the input {} ", inputName);
1892 return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
1894 return Either.left(inputOpt.get());
1899 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1900 groupsAsList.forEach(groupDefinition -> {
1901 groupDefinition.setInvariantName(groupDefinition.getName());
1902 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1906 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1907 if (isEmpty(groups)) {
1910 return updateOrCreateGroups(resource, groups);
1913 private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1914 List<GroupDefinition> groupsFromResource = resource.getGroups();
1915 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1916 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1917 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1918 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1919 if (isNotEmpty(groupsFromResource)) {
1920 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1921 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1923 groupsToCreate.addAll(groupsAsList);
1925 if (isNotEmpty(groupsToCreate)) {
1926 fillGroupsFinalFields(groupsToCreate);
1927 if (isNotEmpty(groupsFromResource)) {
1928 groupBusinessLogic.addGroups(resource, groupsToCreate, true)
1930 .on(this::throwComponentException);
1932 groupBusinessLogic.createGroups(resource, groupsToCreate, true)
1934 .on(this::throwComponentException);
1937 if (isNotEmpty(groupsToDelete)) {
1938 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1940 .on(this::throwComponentException);
1942 if (isNotEmpty(groupsToUpdate)) {
1943 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1945 .on(this::throwComponentException);
1951 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1952 List<GroupDefinition> groupsToDelete) {
1953 for (GroupDefinition group : groupsFromResource) {
1954 Optional<GroupDefinition> op = groupsAsList.stream()
1955 .filter(p -> p.getInvariantName()
1956 .equalsIgnoreCase(group.getInvariantName()))
1958 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
1960 groupsToDelete.add(group);
1965 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1966 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1967 for (GroupDefinition group : groupsAsList) {
1968 Optional<GroupDefinition> op = groupsFromResource.stream()
1969 .filter(p -> p.getInvariantName()
1970 .equalsIgnoreCase(group.getInvariantName()))
1972 if (op.isPresent()) {
1973 GroupDefinition groupToUpdate = op.get();
1974 groupToUpdate.setMembers(group.getMembers());
1975 groupToUpdate.setCapabilities(group.getCapabilities());
1976 groupToUpdate.setProperties(group.getProperties());
1977 groupsToUpdate.add(groupToUpdate);
1979 groupsToCreate.add(group);
1984 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1985 List<InputDefinition> resourceProperties = resource.getInputs();
1986 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1988 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1990 if (createInputs.isRight()) {
1991 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
1992 StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
1994 throw new ByResponseFormatComponentException(createInputs.right()
1997 resource.setInputs(createInputs.left().value());
2002 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
2003 Resource component) {
2005 List<GroupDefinition> result = new ArrayList<>();
2006 List<ComponentInstance> componentInstances = component.getComponentInstances();
2008 if (groups != null) {
2009 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
2010 if (validateCyclicGroupsDependencies.isRight()) {
2011 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
2013 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
2014 String groupName = entry.getKey();
2015 GroupDefinition groupDefinition = entry.getValue();
2016 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2017 updatedGroupDefinition.setMembers(null);
2018 Map<String, String> members = groupDefinition.getMembers();
2019 if (members != null) {
2020 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
2023 result.add(updatedGroupDefinition);
2029 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
2030 Resource component, List<ComponentInstance> componentInstances, String groupName,
2031 Map<String, String> members) {
2032 Set<String> compInstancesNames = members.keySet();
2034 if (CollectionUtils.isEmpty(componentInstances)) {
2035 String membersAstString = compInstancesNames.stream()
2036 .collect(joining(","));
2038 "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
2039 membersAstString, groupName, component.getNormalizedName());
2040 throw new ByActionStatusComponentException(
2041 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2042 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2044 // Find all component instances with the member names
2045 Map<String, String> memberNames = componentInstances.stream()
2046 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2047 memberNames.putAll(groups.keySet()
2049 .collect(toMap(g -> g, g -> "")));
2050 Map<String, String> relevantInstances = memberNames.entrySet()
2052 .filter(n -> compInstancesNames.contains(n.getKey()))
2053 .collect(toMap(Entry::getKey, Entry::getValue));
2055 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2057 List<String> foundMembers = new ArrayList<>();
2058 if (relevantInstances != null) {
2059 foundMembers = relevantInstances.keySet()
2063 compInstancesNames.removeAll(foundMembers);
2064 String membersAstString = compInstancesNames.stream()
2065 .collect(joining(","));
2066 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
2067 component.getNormalizedName());
2068 throw new ByActionStatusComponentException(
2069 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2070 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2072 updatedGroupDefinition.setMembers(relevantInstances);
2076 * This Method validates that there is no cyclic group dependencies. meaning
2077 * group A as member in group B which is member in group A
2082 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
2084 Either<Boolean, ResponseFormat> result = Either.left(true);
2086 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
2088 while (allGroupsItr.hasNext() && result.isLeft()) {
2089 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
2090 // Fetches a group member A
2091 String groupAName = groupAEntry.getKey();
2092 // Finds all group members in group A
2093 Set<String> allGroupAMembersNames = new HashSet<>();
2094 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
2095 // If A is a group member of itself found cyclic dependency
2096 if (allGroupAMembersNames.contains(groupAName)) {
2097 ResponseFormat responseFormat = componentsUtils
2098 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
2099 result = Either.right(responseFormat);
2102 } catch (Exception e) {
2103 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2104 result = Either.right(responseFormat);
2105 log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
2111 * This Method fills recursively the set groupMembers with all the members
2112 * of the given group which are also of type group.
2116 * @param allGroupMembers
2119 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
2120 Set<String> allGroupMembers) {
2122 // Found Cyclic dependency
2123 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
2126 GroupDefinition groupDefinition = allGroups.get(groupName);
2127 // All Members Of Current Group Resource Instances & Other Groups
2128 Set<String> currGroupMembers = groupDefinition.getMembers()
2130 // Filtered Members Of Current Group containing only members which
2132 List<String> currGroupFilteredMembers = currGroupMembers.stream()
2134 // Keep Only Elements of type group and not Resource Instances
2135 filter(allGroups::containsKey)
2137 // Add Filtered Elements to main Set
2138 peek(allGroupMembers::add)
2143 // Recursively call the method for all the filtered group members
2144 for (String innerGroupName : currGroupFilteredMembers) {
2145 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
2150 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
2151 Set<String> allGroupMembers) {
2153 boolean stop = false;
2154 // In Case Not Group Stop
2155 if (!allGroups.containsKey(groupName)) {
2158 // In Case Group Has no members stop
2160 GroupDefinition groupDefinition = allGroups.get(groupName);
2161 stop = isEmpty(groupDefinition.getMembers());
2164 // In Case all group members already contained stop
2166 final Set<String> allMembers = allGroups.get(groupName)
2169 Set<String> membersOfTypeGroup = allMembers.stream()
2171 // Filter In Only Group members
2172 filter(allGroups::containsKey)
2176 stop = allGroupMembers.containsAll(membersOfTypeGroup);
2181 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
2182 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
2183 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2185 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2188 log.debug("************* Going to create all nodes {}", yamlName);
2189 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
2190 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
2191 log.debug("************* Finished to create all nodes {}", yamlName);
2192 log.debug("************* Going to create all resource instances {}", yamlName);
2193 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
2194 resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
2195 csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
2196 log.debug("************* Finished to create all resource instances {}", yamlName);
2197 log.debug("************* Going to create all relations {}", yamlName);
2198 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
2199 log.debug("************* Finished to create all relations {}", yamlName);
2200 log.debug("************* Going to create positions {}", yamlName);
2201 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
2203 log.debug("************* Finished to set positions {}", yamlName);
2207 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
2208 List<ArtifactDefinition> artifactsToAdd) {
2209 List<String> vfcArtifactNames = vfcArtifacts.stream()
2210 .map(ArtifactDataDefinition::getArtifactName)
2212 artifactsToAdd.stream()
2214 if (!vfcArtifactNames.contains(a.getArtifactName())) {
2215 vfcArtifacts.add(a);
2217 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
2223 @SuppressWarnings("unchecked")
2224 private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
2225 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2226 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2227 CsarInfo csarInfo, String nodeName) {
2229 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2230 if (nodeTypeEntry.getValue()
2233 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
2234 csarInfo, nodeTypeEntry.getKey());
2235 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2238 Map<String, Object> mappedToscaTemplate = null;
2239 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
2240 mappedToscaTemplate = nodeTypesInfo.get(nodeName)
2241 .getMappedToscaTemplate();
2243 if (isEmpty(mappedToscaTemplate)) {
2244 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2246 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
2247 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2248 } catch (ComponentException e) {
2249 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
2250 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
2251 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2252 AuditingActionEnum.IMPORT_RESOURCE);
2254 } catch (StorageException e) {
2255 ResponseFormat responseFormat = componentsUtils
2256 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2257 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2258 AuditingActionEnum.IMPORT_RESOURCE);
2263 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
2264 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
2265 boolean inTransaction) {
2267 if (csarInfo.getCsar() != null) {
2268 String vendorLicenseModelId = null;
2269 String vfLicenseModelId = null;
2271 if (artifactOperation.isUpdate()) {
2272 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
2273 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
2274 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
2275 if (artifactEntry.getValue()
2277 .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
2278 vendorLicenseModelId = artifactEntry.getValue()
2281 if (artifactEntry.getValue()
2283 .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
2284 vfLicenseModelId = artifactEntry.getValue()
2291 // Specific Behavior for license artifacts
2292 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2293 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
2294 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
2295 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
2296 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
2297 shouldLock, inTransaction);
2298 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2299 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
2300 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
2301 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
2302 artifactOperation, null, true, shouldLock, inTransaction);
2304 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
2305 createdArtifacts, shouldLock, inTransaction, artifactOperation);
2306 if (eitherCreateResult.isRight()) {
2307 return Either.right(eitherCreateResult.right()
2311 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
2312 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
2314 if (artifacsMetaCsarStatus.isLeft()) {
2315 String artifactsFileName = artifacsMetaCsarStatus.left()
2318 String artifactsContents = artifacsMetaCsarStatus.left()
2321 Either<Resource, ResponseFormat> createArtifactsFromCsar;
2322 if (artifactOperation.isCreateOrLink()) {
2323 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
2324 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
2326 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
2327 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
2329 if ((result.left().value() instanceof Resource) && result.isLeft()) {
2330 Resource service1 = (Resource) result.left().value();
2331 createArtifactsFromCsar = Either.left(service1);
2333 createArtifactsFromCsar = Either.right(result.right().value());
2337 if (createArtifactsFromCsar.isRight()) {
2338 log.debug("Couldn't create artifacts from artifacts.meta");
2339 return Either.right(createArtifactsFromCsar.right()
2343 return Either.left(createArtifactsFromCsar.left()
2347 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
2352 return Either.left(resource);
2355 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
2356 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
2357 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
2358 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
2359 boolean shouldLock, boolean inTransaction) {
2360 byte[] artifactFileBytes = null;
2362 if (csarInfo.getCsar()
2363 .containsKey(artifactPath)) {
2364 artifactFileBytes = csarInfo.getCsar()
2367 Either<Boolean, ResponseFormat> result = Either.left(true);
2368 if (operation.isUpdate() || operation.isDelete()) {
2369 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
2370 Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
2371 .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
2372 resource, shouldLock,
2374 if (handleDelete.isRight()) {
2375 result = Either.right(handleDelete.right()
2378 ArtifactDefinition value = handleDelete.left().value();
2379 String updatedArtifactId = value.getUniqueId();
2380 if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2381 resource.getDeploymentArtifacts().remove(updatedArtifactId);
2383 resource.getArtifacts().remove(updatedArtifactId);
2389 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2390 operation = new ArtifactOperationInfo(false, false,
2391 ArtifactOperationEnum.CREATE);
2395 if (artifactFileBytes != null) {
2396 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
2397 artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
2398 artifactDescription, artifactFileBytes, null, isFromCsar);
2399 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
2400 .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
2402 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2403 if (eitherNonMetaArtifacts.isRight()) {
2404 BeEcompErrorManager.getInstance()
2405 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2406 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2407 ErrorSeverity.WARNING);
2408 return Either.right(eitherNonMetaArtifacts.right()
2411 ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
2412 createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
2418 private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
2419 if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
2420 resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
2422 resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
2426 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2427 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2430 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2431 List<ArtifactDefinition> createdArtifacts,
2432 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2433 if (operation.isCreateOrLink() && createdArtifacts != null
2434 && eitherNonMetaArtifacts.isLeft()) {
2435 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
2437 if (eitherResult.isLeft()) {
2438 createdArtifacts.add(eitherResult.left()
2444 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2445 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2446 ArtifactOperationInfo artifactOperation) {
2448 Either<Resource, ResponseFormat> resStatus = null;
2449 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2452 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
2453 collectedWarningMessages);
2454 if (artifactPathAndNameList.isRight()) {
2455 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2456 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
2459 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2461 if (artifactOperation.isCreateOrLink()) {
2462 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2463 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
2466 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2467 resource, artifactPathAndNameList.left()
2469 csarInfo.getModifier());
2471 if (findVfCsarArtifactsToHandleRes.isRight()) {
2472 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
2475 if (resStatus == null) {
2476 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
2480 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2481 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
2482 resStatus, vfCsarArtifactsToHandle);
2484 if (resStatus == null) {
2485 resStatus = Either.left(resource);
2487 } catch (Exception e) {
2488 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2489 log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2491 CsarUtils.handleWarningMessages(collectedWarningMessages);
2496 private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
2497 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2498 Either<Resource, ResponseFormat> resStatus,
2499 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2500 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2503 Optional<ResponseFormat> optionalCreateInDBError =
2504 // Stream of artifacts to be created
2505 currArtifactOperationPair.getValue()
2507 // create each artifact
2508 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2509 e.getArtifactName(), e.getArtifactType(),
2510 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2511 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2512 new ArtifactOperationInfo(false, false,
2513 currArtifactOperationPair.getKey()),
2514 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2515 // filter in only error
2516 .filter(Either::isRight)
2518 // Convert the error from either to
2523 // Check if an error occurred
2525 // Error found on artifact Creation
2526 if (optionalCreateInDBError.isPresent()) {
2527 resStatus = Either.right(optionalCreateInDBError.get());
2534 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
2535 Map<String, Set<List<String>>> collectedWarningMessages) {
2536 List<NonMetaArtifactInfo> artifactPathAndNameList =
2537 // Stream of file paths contained in csar
2541 // Filter in only VF artifact path location
2542 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
2543 .matcher(e.getKey())
2545 // Validate and add warnings
2546 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2547 // Filter in Non Warnings
2548 .filter(Either::isLeft)
2549 // Convert from Either to NonMetaArtifactInfo
2554 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2555 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2556 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
2558 return Either.right(nonMetaArtifactInfo.getArtifactName());
2561 return Either.left(artifactPathAndNameList);
2564 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2565 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2567 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2568 // collect all Deployment and Informational artifacts of VF
2569 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
2571 existingArtifacts.addAll(resource.getDeploymentArtifacts()
2574 if (resource.getArtifacts() != null && !resource.getArtifacts()
2576 existingArtifacts.addAll(resource.getArtifacts()
2579 existingArtifacts = existingArtifacts.stream()
2580 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2581 // was created from HEAT.meta
2582 .filter(this::isNonMetaArtifact)
2585 List<String> artifactsToIgnore = new ArrayList<>();
2586 // collect IDs of Artifacts of VF which belongs to any group
2587 if (resource.getGroups() != null) {
2588 resource.getGroups()
2591 if (g.getArtifacts() != null && !g.getArtifacts()
2593 artifactsToIgnore.addAll(g.getArtifacts());
2597 existingArtifacts = existingArtifacts.stream()
2598 // filter artifacts which belongs to any group
2599 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
2601 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2604 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2605 boolean result = true;
2606 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2612 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2613 boolean result = true;
2614 if (artifact.getArtifactType() == null
2615 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2616 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2622 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
2623 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
2624 log.debug("#createResourceInstancesRelations - Going to create relations ");
2625 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations");
2626 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2627 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
2628 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
2630 "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
2631 resource.getUniqueId(), yamlName);
2632 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
2633 BeEcompErrorManager.getInstance()
2634 .logInternalDataError("createResourceInstancesRelations",
2635 "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2636 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2638 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2639 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2640 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2641 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2642 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2643 Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
2644 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2645 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2647 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2648 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2649 if (allDataTypes.isRight()) {
2650 JanusGraphOperationStatus status = allDataTypes.right()
2652 BeEcompErrorManager.getInstance()
2653 .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2654 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2655 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2656 StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
2657 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2658 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
2661 Resource finalResource = resource;
2662 uploadResInstancesMap.values()
2663 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2664 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
2665 instAttributes, existingNodeTypesByResourceNames, instInputs, i));
2666 resource.getComponentInstances()
2668 .filter(i -> !i.isCreatedFromCsar())
2669 .forEach(i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements,
2670 instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
2672 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2673 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2674 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2675 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2676 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2677 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2678 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2679 associateResourceInstances(yamlName, resource, relations);
2680 handleSubstitutionMappings(resource, uploadResInstancesMap);
2681 log.debug("************* in create relations, getResource start");
2682 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations");
2683 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2684 .getToscaFullElement(resource.getUniqueId());
2685 log.debug("************* in create relations, getResource end");
2686 if (eitherGetResource.isRight()) {
2687 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2688 StatusCode.ERROR,"ERROR while create relations");
2689 throw new ByResponseFormatComponentException(componentsUtils
2690 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
2691 .value()), resource));
2693 return eitherGetResource.left()
2697 private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
2698 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2699 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2700 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2701 Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String,
2702 List<ComponentInstanceProperty>> instProperties, Map<String,
2703 List<ComponentInstanceInput>> instInputs,
2704 Map<String, List<AttributeDefinition>> instAttributes) {
2705 Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
2706 if (foundInstance.isPresent()) {
2707 if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) {
2708 instCapabilities.put(instance, foundInstance.get().getCapabilities());
2710 if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) {
2711 instRequirements.put(instance, foundInstance.get().getRequirements());
2713 if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) {
2714 instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
2716 if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
2717 instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
2719 if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
2721 .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
2722 instProperties.put(instance.getUniqueId(),
2723 oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
2725 if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
2727 .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
2728 instInputs.put(instance.getUniqueId(),
2729 oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
2731 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
2732 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
2733 instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new).collect(toList()));
2738 private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
2739 if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
2740 return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
2742 return Optional.empty();
2745 private void associateResourceInstances(String yamlName, Resource resource,
2746 List<RequirementCapabilityRelDef> relations) {
2747 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2749 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2750 StorageOperationStatus status = relationsEither.right().value();
2751 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2753 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
2755 setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
2759 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2760 Map<String, List<AttributeDefinition>> instAttributes) {
2761 StorageOperationStatus addArtToInst;
2762 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2764 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2765 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2767 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst),
2772 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2773 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2774 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2775 StorageOperationStatus addArtToInst;
2776 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2778 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2779 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2781 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2785 private void associateArtifactsToInstances(String yamlName, Resource resource,
2786 Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2787 StorageOperationStatus addArtToInst;
2789 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2790 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2791 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2792 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2796 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2797 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2798 StorageOperationStatus addArtToInst = toscaOperationFacade
2799 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2800 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2801 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2802 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2806 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2807 Map<String, List<ComponentInstanceInput>> instInputs) {
2808 if (MapUtils.isNotEmpty(instInputs)) {
2809 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2810 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2811 if (addInputToInst.isRight()) {
2813 StorageOperationStatus addInputToInstError = addInputToInst.right().value();
2814 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2815 addInputToInstError);
2816 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
2818 setComponentInstanceInputsOnComponent(resource, instInputs);
2822 private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2823 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
2824 if (componentInstancesInputs == null)
2825 componentInstancesInputs = new HashMap<>();
2826 componentInstancesInputs.putAll(instInputs);
2827 resource.setComponentInstancesInputs(componentInstancesInputs);
2830 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2831 Map<String, List<ComponentInstanceProperty>> instProperties) {
2832 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2833 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2834 if (addPropToInst.isRight()) {
2835 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2836 StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
2837 StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
2838 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2839 storageOperationStatus);
2840 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
2842 setComponentInstancePropertiesOnComponent(resource, instProperties);
2845 private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2846 Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
2847 if (componentInstanceProps == null )
2848 componentInstanceProps = new HashMap<>();
2849 componentInstanceProps.putAll(instProperties);
2850 resource.setComponentInstancesProperties(componentInstanceProps);
2853 private void handleSubstitutionMappings(Resource resource,
2854 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2855 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2856 Either<Resource, StorageOperationStatus> getResourceRes =
2857 updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
2858 if (getResourceRes.isRight()) {
2859 ResponseFormat responseFormat = componentsUtils
2860 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
2861 .value()), resource);
2862 throw new ByResponseFormatComponentException(responseFormat);
2867 private void addRelationsToRI(String yamlName, Resource resource,
2868 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2869 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2870 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2871 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2872 ComponentInstance currentCompInstance = null;
2873 for (ComponentInstance compInstance : componentInstancesList) {
2875 if (compInstance.getName()
2876 .equals(uploadComponentInstanceInfo.getName())) {
2877 currentCompInstance = compInstance;
2882 if (currentCompInstance == null) {
2883 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2884 resource.getUniqueId());
2885 BeEcompErrorManager.getInstance()
2886 .logInternalDataError(
2887 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2888 resource.getUniqueId(), ErrorSeverity.ERROR);
2889 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2892 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2893 if (addRelationToRiRes.getStatus() != 200) {
2894 throw new ByResponseFormatComponentException(addRelationToRiRes);
2900 private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
2901 if (resource.getComponentInstancesRelations() != null) {
2902 resource.getComponentInstancesRelations().addAll(relations);
2904 resource.setComponentInstancesRelations(relations);
2908 private void processComponentInstance(String yamlName, Resource resource,
2909 List<ComponentInstance> componentInstancesList,
2910 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2911 Map<String, List<ComponentInstanceProperty>> instProperties,
2912 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2913 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2914 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2915 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
2916 Map<String, List<AttributeDefinition>> instAttributes,
2917 Map<String, Resource> originCompMap,
2918 Map<String, List<ComponentInstanceInput>> instInputs,
2919 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2920 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2921 .filter(i -> i.getName()
2922 .equals(uploadComponentInstanceInfo.getName()))
2924 if (!currentCompInstanceOpt.isPresent()) {
2925 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2926 resource.getUniqueId());
2927 BeEcompErrorManager.getInstance()
2928 .logInternalDataError(
2929 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2930 resource.getUniqueId(), ErrorSeverity.ERROR);
2931 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2933 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2934 String resourceInstanceId = currentCompInstance.getUniqueId();
2935 Resource originResource = getOriginResource(originCompMap, currentCompInstance);
2936 if (isNotEmpty(originResource.getRequirements())) {
2937 instRequirements.put(currentCompInstance, originResource.getRequirements());
2939 if (isNotEmpty(originResource.getCapabilities())) {
2940 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2941 currentCompInstance, originResource);
2943 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
2945 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2947 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2948 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2950 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2951 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2953 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2954 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2955 originResource, currentCompInstance, instProperties, allDataTypes.left()
2957 if (addPropertiesValueToRiRes.getStatus() != 200) {
2958 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2961 addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
2967 private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2968 Resource originResource;
2969 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2970 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2971 .getToscaFullElement(currentCompInstance.getComponentUid());
2972 if (getOriginResourceRes.isRight()) {
2973 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2974 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2975 getOriginResourceRes);
2976 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
2977 .value()), currentCompInstance.getComponentUid());
2979 originResource = getOriginResourceRes.left()
2981 originCompMap.put(originResource.getUniqueId(), originResource);
2983 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2985 return originResource;
2988 private void processComponentInstanceCapabilities(
2989 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2990 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2991 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2992 Resource originResource) {
2993 Map<String, List<CapabilityDefinition>> originCapabilities;
2994 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2995 originCapabilities = new HashMap<>();
2996 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2997 originResource.getCapabilities()
2998 .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
2999 uploadComponentInstanceInfo.getCapabilities()
3001 .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
3002 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
3004 originCapabilities = originResource.getCapabilities();
3006 instCapabilties.put(currentCompInstance, originCapabilities);
3009 private void updateCapabilityPropertiesValues(
3010 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
3011 Map<String, List<CapabilityDefinition>> originCapabilities,
3012 Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
3013 originCapabilities.values()
3015 .flatMap(Collection::stream)
3016 .filter(c -> newPropertiesMap.containsKey(c.getName()))
3017 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
3022 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
3023 List<UploadCapInfo> capabilities) {
3024 for (UploadCapInfo capability : capabilities) {
3025 if (isNotEmpty(capability.getProperties())) {
3026 newPropertiesMap.put(capability.getName(), capability.getProperties()
3028 .collect(toMap(UploadInfo::getName, p -> p)));
3033 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
3034 List<CapabilityDefinition> capabilities) {
3035 List<CapabilityDefinition> list = capabilities.stream()
3036 .map(CapabilityDefinition::new)
3038 originCapabilities.put(type, list);
3041 private void updatePropertyValues(List<ComponentInstanceProperty> properties,
3042 Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
3043 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
3046 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
3047 Map<String, DataTypeDefinition> allDataTypes) {
3048 String value = null;
3049 List<GetInputValueDataDefinition> getInputs = null;
3050 boolean isValidate = true;
3051 if (null != propertyInfo && propertyInfo.getValue() != null) {
3052 getInputs = propertyInfo.getGet_input();
3053 isValidate = getInputs == null || getInputs.isEmpty();
3055 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
3057 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3058 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3061 property.setValue(value);
3062 return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3065 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
3066 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3067 Either<Resource, StorageOperationStatus> updateRes = null;
3068 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3069 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3070 StorageOperationStatus status = toscaOperationFacade
3071 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
3072 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3074 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
3075 resource.getUniqueId(), status);
3076 updateRes = Either.right(status);
3078 if (updateRes == null) {
3079 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
3080 updatedInstCapabilities, updatedInstRequirements);
3081 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
3082 updatedInstRequirements, resource);
3083 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3085 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
3086 resource.getUniqueId(), status);
3087 updateRes = Either.right(status);
3090 if (updateRes == null) {
3091 updateRes = Either.left(resource);
3096 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
3097 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3098 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
3099 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3101 componentInstances.stream()
3103 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
3104 .getCapabilitiesNamesToUpdate());
3105 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
3106 .getRequirementsNamesToUpdate());
3110 private void fillUpdatedInstRequirements(
3111 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
3112 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3113 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3114 Set<String> updatedReqNames = new HashSet<>();
3115 if (isNotEmpty(requirementsNamesToUpdate)) {
3116 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
3118 updatedRequirements.put(requirements.getKey(), requirements.getValue()
3120 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
3121 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3123 r.setParentName(r.getName());
3124 r.setName(requirementsNamesToUpdate.get(r.getName()));
3125 updatedReqNames.add(r.getName());
3128 .collect(toList()));
3131 if (isNotEmpty(updatedRequirements)) {
3132 updatedInstRequirements.put(instance, updatedRequirements);
3136 private void fillUpdatedInstCapabilities(
3137 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
3138 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3139 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3140 Set<String> updatedCapNames = new HashSet<>();
3141 if (isNotEmpty(capabilitiesNamesToUpdate)) {
3142 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
3144 updatedCapabilities.put(requirements.getKey(), requirements.getValue()
3146 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
3147 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3149 c.setParentName(c.getName());
3150 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
3151 updatedCapNames.add(c.getName());
3154 .collect(toList()));
3157 if (isNotEmpty(updatedCapabilities)) {
3158 updatedInstCapabilties.put(instance, updatedCapabilities);
3162 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
3163 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3164 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3166 ComponentInstance currentCompInstance = null;
3168 for (ComponentInstance compInstance : componentInstancesList) {
3170 if (compInstance.getName()
3171 .equals(nodesInfoValue.getName())) {
3172 currentCompInstance = compInstance;
3178 if (currentCompInstance == null) {
3179 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
3180 BeEcompErrorManager.getInstance()
3181 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
3182 resource.getUniqueId(), ErrorSeverity.ERROR);
3183 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3185 String resourceInstanceId = currentCompInstance.getUniqueId();
3187 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
3189 if (regMap != null) {
3190 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
3193 while (nodesRegValue.hasNext()) {
3194 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3196 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3197 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3198 log.debug("Going to create relation {}", uploadRegInfo.getName());
3199 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
3200 String regName = uploadRegInfo.getName();
3201 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3202 regCapRelDef.setFromNode(resourceInstanceId);
3203 log.debug("try to find available requirement {} ", regName);
3204 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3205 yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
3206 if (eitherReqStatus.isRight()) {
3207 log.debug("failed to find available requirement {} status is {}", regName,
3208 eitherReqStatus.right()
3210 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
3211 return eitherReqStatus.right()
3215 RequirementDefinition validReq = eitherReqStatus.left()
3217 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3218 .getRelationships();
3219 if (reqAndRelationshipPairList == null) {
3220 reqAndRelationshipPairList = new ArrayList<>();
3222 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3223 reqAndRelationshipPair.setRequirement(regName);
3224 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3225 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3226 RelationshipImpl relationship = new RelationshipImpl();
3227 relationship.setType(validReq.getCapability());
3228 reqAndRelationshipPair.setRelationships(relationship);
3230 ComponentInstance currentCapCompInstance = null;
3231 for (ComponentInstance compInstance : componentInstancesList) {
3232 if (compInstance.getName()
3233 .equals(uploadRegInfo.getNode())) {
3234 currentCapCompInstance = compInstance;
3239 if (currentCapCompInstance == null) {
3240 log.debug("The component instance with name {} not found on resource {} ",
3241 uploadRegInfo.getNode(), resource.getUniqueId());
3242 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
3243 BeEcompErrorManager.getInstance()
3244 .logInternalDataError(
3245 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
3246 resource.getUniqueId(), ErrorSeverity.ERROR);
3247 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3249 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3250 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3251 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3252 currentCapCompInstance, uploadRegInfo);
3254 if (aviableCapForRel == null) {
3255 log.debug("aviable capability was not found. req name is {} component instance is {}",
3256 validReq.getName(), currentCapCompInstance.getUniqueId());
3257 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());
3258 BeEcompErrorManager.getInstance()
3259 .logInternalDataError(
3260 "aviable capability was not found. req name is " + validReq.getName()
3261 + " component instance is " + currentCapCompInstance.getUniqueId(),
3262 resource.getUniqueId(), ErrorSeverity.ERROR);
3263 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3265 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3266 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3267 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3269 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3270 capReqRel.setRelation(reqAndRelationshipPair);
3271 reqAndRelationshipPairList.add(capReqRel);
3272 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3273 relations.add(regCapRelDef);
3276 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3277 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3279 return componentsUtils.getResponseFormat(ActionStatus.OK);
3282 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
3283 Resource originResource, ComponentInstance currentCompInstance,
3284 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3285 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3286 if (MapUtils.isNotEmpty(propMap)) {
3287 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
3288 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3290 if (CollectionUtils.isEmpty(originResource.getInputs())) {
3291 log.debug("failed to find properties ");
3292 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
3293 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
3295 originResource.getInputs()
3296 .forEach(p -> addInput(currPropertiesMap, p));
3297 for (List<UploadPropInfo> propertyList : propMap.values()) {
3298 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
3301 currPropertiesMap.values()
3302 .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
3303 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3307 private void processProperty(Resource resource, ComponentInstance currentCompInstance,
3308 Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
3309 List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
3310 UploadPropInfo propertyInfo = propertyList.get(0);
3311 String propName = propertyInfo.getName();
3312 if (!currPropertiesMap.containsKey(propName)) {
3313 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3314 StatusCode.ERROR,"ERROR failed to find property: {}",propName);
3315 log.debug("failed to find property {} ", propName);
3316 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
3318 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3319 ComponentInstanceInput property = null;
3321 String value = null;
3322 List<GetInputValueDataDefinition> getInputs = null;
3323 boolean isValidate = true;
3324 if (propertyInfo.getValue() != null) {
3325 getInputs = propertyInfo.getGet_input();
3326 isValidate = getInputs == null || getInputs.isEmpty();
3328 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3330 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3331 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3334 property = new ComponentInstanceInput(curPropertyDef, value, null);
3336 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3338 property.setValue(validPropertyVAlue);
3340 if (isNotEmpty(getInputs)) {
3341 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3342 for (GetInputValueDataDefinition getInput : getInputs) {
3343 List<InputDefinition> inputs = resource.getInputs();
3344 if (CollectionUtils.isEmpty(inputs)) {
3345 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3346 StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
3347 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
3348 currentCompInstance.getUniqueId());
3349 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3352 Optional<InputDefinition> optional = inputs.stream()
3353 .filter(p -> p.getName()
3354 .equals(getInput.getInputName()))
3356 if (!optional.isPresent()) {
3357 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3358 StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
3359 log.debug("Failed to find input {} ", getInput.getInputName());
3360 // @@TODO error message
3361 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3363 InputDefinition input = optional.get();
3364 getInput.setInputId(input.getUniqueId());
3365 getInputValues.add(getInput);
3367 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3368 processGetInput(getInputValues, inputs, getInputIndex);
3370 property.setGetInputValues(getInputValues);
3372 instPropList.add(property);
3373 // delete overriden property
3374 currPropertiesMap.remove(property.getName());
3377 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
3378 GetInputValueDataDefinition getInputIndex) {
3379 Optional<InputDefinition> optional;
3380 if (getInputIndex != null) {
3381 optional = inputs.stream()
3382 .filter(p -> p.getName()
3383 .equals(getInputIndex.getInputName()))
3385 if (!optional.isPresent()) {
3386 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3387 // @@TODO error message
3388 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3390 InputDefinition inputIndex = optional.get();
3391 getInputIndex.setInputId(inputIndex.getUniqueId());
3392 getInputValues.add(getInputIndex);
3396 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
3397 String propName = prop.getName();
3398 if (!currPropertiesMap.containsKey(propName)) {
3399 currPropertiesMap.put(propName, prop);
3403 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3404 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
3405 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3407 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3408 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
3410 List<PropertyDefinition> listFromMap = originResource.getProperties();
3411 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3412 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3413 StatusCode.ERROR,"ERROR Failed to find properties");
3414 log.debug("failed to find properties");
3415 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3417 if (listFromMap == null || listFromMap.isEmpty()) {
3418 return componentsUtils.getResponseFormat(ActionStatus.OK);
3420 for (PropertyDefinition prop : listFromMap) {
3421 String propName = prop.getName();
3422 if (!currPropertiesMap.containsKey(propName)) {
3423 currPropertiesMap.put(propName, prop);
3426 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3427 if (propMap != null && propMap.size() > 0) {
3428 for (List<UploadPropInfo> propertyList : propMap.values()) {
3430 UploadPropInfo propertyInfo = propertyList.get(0);
3431 String propName = propertyInfo.getName();
3432 if (!currPropertiesMap.containsKey(propName)) {
3433 log.debug("failed to find property {} ", propName);
3434 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
3435 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3437 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3438 ComponentInstanceProperty property = null;
3440 String value = null;
3441 List<GetInputValueDataDefinition> getInputs = null;
3442 boolean isValidate = true;
3443 if (propertyInfo.getValue() != null) {
3444 getInputs = propertyInfo.getGet_input();
3445 isValidate = getInputs == null || getInputs.isEmpty();
3447 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3449 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3450 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3453 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3455 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3456 property.setValue(validatePropValue);
3458 if (getInputs != null && !getInputs.isEmpty()) {
3459 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3460 for (GetInputValueDataDefinition getInput : getInputs) {
3461 List<InputDefinition> inputs = resource.getInputs();
3462 if (inputs == null || inputs.isEmpty()) {
3463 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
3464 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
3465 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
3467 .map(GetInputValueDataDefinition::getInputName)
3471 Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
3472 if (inputEither.isRight()) {
3473 throw inputEither.right().value();
3475 InputDefinition input = inputEither.left().value();
3476 getInput.setInputId(input.getUniqueId());
3477 getInputValues.add(getInput);
3479 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3480 if (getInputIndex != null) {
3481 Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
3483 if (inputEither.isRight()) {
3484 throw newInputEither.right().value();
3486 InputDefinition newInput = newInputEither.left().value();
3487 getInputIndex.setInputId(newInput.getUniqueId());
3489 getInputValues.add(getInputIndex);
3494 property.setGetInputValues(getInputValues);
3496 instPropList.add(property);
3497 // delete overriden property
3498 currPropertiesMap.remove(property.getName());
3501 // add rest of properties
3502 if (!currPropertiesMap.isEmpty()) {
3503 for (PropertyDefinition value : currPropertiesMap.values()) {
3504 instPropList.add(new ComponentInstanceProperty(value));
3507 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3508 return componentsUtils.getResponseFormat(ActionStatus.OK);
3511 // US740820 Relate RIs according to capability name
3512 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3513 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3514 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
3515 .equals(uploadReqInfo.getCapabilityName())) {// get
3519 return findAvailableCapability(validReq, currentCapCompInstance);
3521 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3524 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3525 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3526 CapabilityDefinition cap = null;
3527 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3528 if (!capMap.containsKey(validReq.getCapability())) {
3531 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
3533 .filter(p -> p.getName()
3534 .equals(uploadReqInfo.getCapabilityName()))
3536 if (!capByName.isPresent()) {
3539 cap = capByName.get();
3541 if (isBoundedByOccurrences(cap)) {
3542 String leftOccurrences = cap.getLeftOccurrences();
3543 int left = Integer.parseInt(leftOccurrences);
3546 cap.setLeftOccurrences(String.valueOf(left));
3554 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
3555 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
3556 if (capMap.containsKey(validReq.getCapability())) {
3557 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3559 for (CapabilityDefinition cap : capList) {
3560 if (isBoundedByOccurrences(cap)) {
3561 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
3562 : cap.getMaxOccurrences();
3563 int left = Integer.parseInt(leftOccurrences);
3566 cap.setLeftOccurrences(String.valueOf(left));
3577 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
3578 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
3579 .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
3582 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3583 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3585 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3586 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3587 RequirementDefinition validRegDef = null;
3589 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3590 for (RequirementDefinition reqDef : entry.getValue()) {
3591 if (reqDef.getName()
3593 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3594 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3595 String leftOccurrences = reqDef.getLeftOccurrences();
3596 if (leftOccurrences == null) {
3597 leftOccurrences = reqDef.getMaxOccurrences();
3599 int left = Integer.parseInt(leftOccurrences);
3602 reqDef.setLeftOccurrences(String.valueOf(left));
3603 validRegDef = reqDef;
3609 validRegDef = reqDef;
3615 if (validRegDef != null) {
3620 for (RequirementDefinition reqDef : list) {
3621 if (reqDef.getName()
3623 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3624 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3625 String leftOccurrences = reqDef.getLeftOccurrences();
3626 if (leftOccurrences == null) {
3627 leftOccurrences = reqDef.getMaxOccurrences();
3629 int left = Integer.parseInt(leftOccurrences);
3632 reqDef.setLeftOccurrences(String.valueOf(left));
3633 validRegDef = reqDef;
3639 validRegDef = reqDef;
3645 if (validRegDef == null) {
3646 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3647 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3648 return Either.right(responseFormat);
3650 return Either.left(validRegDef);
3653 private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
3654 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
3656 Either<Resource, ResponseFormat> eitherResource;
3657 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3658 if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3659 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3660 throw new ByResponseFormatComponentException(responseFormat);
3662 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3663 nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
3665 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3666 uploadResInstancesMap.values()
3667 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
3668 existingNodeTypesByResourceNames, resourcesInstancesMap));
3669 if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
3670 Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
3672 .collect(toMap(Resource::getUniqueId, r -> r));
3673 oldResource.getComponentInstances()
3675 .filter(i -> !i.isCreatedFromCsar())
3676 .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
3677 getOriginResource(existingNodeTypesByUids, uiInst)));
3680 if (isNotEmpty(resourcesInstancesMap)) {
3682 toscaOperationFacade.associateComponentInstancesToComponent(resource,
3683 resourcesInstancesMap, false, oldResource != null);
3684 } catch (StorageException exp) {
3685 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
3686 log.debug("Failed to add component instances to container component {}", resource.getName());
3687 ResponseFormat responseFormat = componentsUtils
3688 .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
3689 eitherResource = Either.right(responseFormat);
3690 throw new ByResponseFormatComponentException(eitherResource.right().value());
3694 if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
3695 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3696 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3697 BeEcompErrorManager.getInstance()
3698 .logBeDaoSystemError(
3699 "Error when create resource instance from csar. ComponentInstances list empty");
3700 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3705 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3706 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
3707 Map<ComponentInstance, Resource> resourcesInstancesMap) {
3708 Either<Resource, ResponseFormat> eitherResource;
3709 log.debug("*************Going to create resource instances {}", yamlName);
3710 // updating type if the type is node type name - we need to take the
3712 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3713 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3714 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
3715 .getToscaResourceName());
3717 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3718 existingnodeTypeMap, resource);
3720 ComponentInstance componentInstance = new ComponentInstance();
3721 componentInstance.setComponentUid(refResource.getUniqueId());
3722 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3723 if(directives != null && !directives.isEmpty()) {
3724 componentInstance.setDirectives(new ArrayList<>(directives));
3726 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3727 if (uploadNodeFilterInfo != null){
3728 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3729 componentInstance.getUniqueId()));
3731 ComponentTypeEnum containerComponentType = resource.getComponentType();
3732 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3733 if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3734 && isNotEmpty(refResource.getCapabilities())) {
3735 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3736 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3737 refResource.getUniqueId(), refResource.getCapabilities(),
3738 uploadComponentInstanceInfo.getCapabilities());
3739 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3742 if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
3743 Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
3744 Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
3745 Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
3746 .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
3747 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
3748 Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
3749 for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
3750 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
3751 to.setFile(entry.getValue().getFile());
3752 to.setType(entry.getValue().getType());
3753 toscaArtifacts.put(entry.getKey(), to);
3755 componentInstance.setToscaArtifacts(toscaArtifacts);
3758 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3759 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
3760 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3761 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3762 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3764 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3765 componentInstance.setName(uploadComponentInstanceInfo.getName());
3766 componentInstance.setIcon(origResource.getIcon());
3767 componentInstance.setCreatedFrom(CreatedFrom.CSAR);
3768 resourcesInstancesMap.put(componentInstance, origResource);
3771 private ComponentParametersView getComponentWithInstancesFilter() {
3772 ComponentParametersView parametersView = new ComponentParametersView();
3773 parametersView.disableAll();
3774 parametersView.setIgnoreComponentInstances(false);
3775 parametersView.setIgnoreInputs(false);
3776 // inputs are read when creating
3777 // property values on instances
3778 parametersView.setIgnoreUsers(false);
3779 return parametersView;
3782 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3783 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3784 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3785 if (originCapabilities.containsKey(currEntry.getKey())) {
3786 currEntry.getValue()
3788 .forEach(cap -> cap.setType(currEntry.getKey()));
3791 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3792 capabilities.getValue()
3795 if (uploadedCapabilities.containsKey(cap.getName())) {
3796 uploadedCapabilities.get(cap.getName())
3799 c.setName(cap.getName());
3800 c.setType(cap.getType());
3807 private Resource validateResourceInstanceBeforeCreate(String yamlName,
3808 UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap, Resource resource) {
3811 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
3812 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3813 Resource refResource;
3814 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3815 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3817 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3818 .getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(),
3819 ((ResourceMetadataDataDefinition)resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease());
3820 if (findResourceEither.isRight()) {
3822 "validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}",
3823 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3824 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3826 refResource = findResourceEither.left().value();
3827 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3829 String componentState = refResource.getComponentMetadataDefinition()
3830 .getMetadataDataDefinition()
3832 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3834 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3835 refResource.getName(), componentState);
3836 throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
3837 refResource.getComponentType().getValue(),refResource.getName(), componentState);
3840 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3841 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3842 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3843 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3848 public Resource propagateStateToCertified(User user, Resource resource,
3849 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3850 boolean forceCertificationAllowed) {
3852 boolean failed = false;
3854 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3855 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3856 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3858 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3859 Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
3860 resource, user, false, inTransaction, needLock, false);
3863 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3864 } catch (ComponentException e) {
3866 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3870 BeEcompErrorManager.getInstance()
3871 .logBeSystemError("Change LifecycleState - Certify");
3872 if (!inTransaction) {
3873 janusGraphDao.rollback();
3875 } else if (!inTransaction) {
3876 janusGraphDao.commit();
3881 private Resource nodeFullCertification(String uniqueId, User user,
3882 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3883 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
3884 inTransaction, needLock);
3885 if(resourceResponse.isRight()){
3886 throw new ByResponseFormatComponentException(resourceResponse.right().value());
3888 return resourceResponse.left().value();
3891 private Resource nodeForceCertification(Resource resource, User user,
3892 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3893 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3897 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
3899 final boolean isNormative,
3900 final boolean isInTransaction,
3901 final boolean needLock,
3902 final CsarInfo csarInfo,
3903 final String nodeName,
3904 final boolean isNested) {
3906 ImmutablePair<Resource, ActionStatus> result = null;
3907 // check if resource already exists (search by tosca name = type)
3908 final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3909 final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3910 .getLatestByToscaResourceName(resource.getToscaResourceName());
3912 if (latestByToscaName.isLeft()) {
3913 Resource foundResource = latestByToscaName.left().value();
3914 // we don't allow updating names of top level types
3915 if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
3916 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3917 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3918 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3919 foundResource.getName(), resource.getToscaResourceName());
3920 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3921 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3922 throwComponentException(responseFormat);
3924 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3925 } else if (isNotFound(latestByToscaName)) {
3926 if (isNestedResource) {
3927 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
3928 isNested, nodeName);
3930 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3933 StorageOperationStatus status = latestByToscaName.right().value();
3934 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3935 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
3936 .convertFromStorageResponse(latestByToscaName.right().value()), resource);
3937 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3938 throwComponentException(responseFormat);
3943 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3944 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3947 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
3949 final boolean isNormative,
3950 final boolean isInTransaction,
3951 final boolean needLock,
3952 final CsarInfo csarInfo,
3953 final boolean isNested,
3954 final String nodeName) {
3955 final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3956 .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
3957 .name(), csarInfo.getVfResourceName(), nodeName).getRight());
3958 if (latestByToscaName.isLeft()) {
3959 final Resource nestedResource = (Resource) latestByToscaName.left().value();
3960 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3961 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
3962 resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3963 if (eitherValidation.isRight()) {
3964 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3966 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3968 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3972 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3973 return getResourceEither.isRight() && getResourceEither.right()
3974 .value() == StorageOperationStatus.NOT_FOUND;
3977 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
3978 boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3979 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3980 validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3981 final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
3983 Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
3984 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
3985 ASDCKpiApi.countImportResourcesKPI();
3986 return resourcePair;
3989 public boolean isResourceExist(String resourceName) {
3990 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3991 return latestByName.isLeft();
3994 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
3995 Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
3996 String lockedResourceId = oldResource.getUniqueId();
3997 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3998 oldResource.getVersion(), oldResource.getLifecycleState());
3999 ImmutablePair<Resource, ActionStatus> resourcePair = null;
4001 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
4002 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
4003 mergeOldResourceMetadataWithNew(oldResource, newResource);
4005 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
4006 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
4007 // contact info normalization
4008 newResource.setContactId(newResource.getContactId().toLowerCase());
4009 PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
4010 // non-updatable fields
4011 newResource.setCreatorUserId(user.getUserId());
4012 newResource.setCreatorFullName(user.getFullName());
4013 newResource.setLastUpdaterUserId(user.getUserId());
4014 newResource.setLastUpdaterFullName(user.getFullName());
4015 newResource.setUniqueId(oldResource.getUniqueId());
4016 newResource.setVersion(oldResource.getVersion());
4017 newResource.setInvariantUUID(oldResource.getInvariantUUID());
4018 newResource.setLifecycleState(oldResource.getLifecycleState());
4019 newResource.setUUID(oldResource.getUUID());
4020 newResource.setNormalizedName(oldResource.getNormalizedName());
4021 newResource.setSystemName(oldResource.getSystemName());
4022 if (oldResource.getCsarUUID() != null) {
4023 newResource.setCsarUUID(oldResource.getCsarUUID());
4025 if (oldResource.getImportedToscaChecksum() != null) {
4026 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
4028 newResource.setAbstract(oldResource.isAbstract());
4030 if (CollectionUtils.isEmpty(newResource.getDerivedFrom())){
4031 newResource.setDerivedFrom(oldResource.getDerivedFrom());
4033 if (CollectionUtils.isEmpty(newResource.getDataTypes())){
4034 newResource.setDataTypes(oldResource.getDataTypes());
4036 if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())){
4037 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
4039 if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())){
4040 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
4043 // created without tosca artifacts - add the placeholders
4044 if (MapUtils.isEmpty(newResource.getToscaArtifacts())){
4045 setToscaArtifactsPlaceHolders(newResource, user);
4048 if (MapUtils.isEmpty(newResource.getInterfaces())){
4049 newResource.setInterfaces(oldResource.getInterfaces());
4051 if (CollectionUtils.isEmpty(newResource.getAttributes())) {
4052 newResource.setAttributes(oldResource.getAttributes());
4055 if (CollectionUtils.isEmpty(newResource.getProperties())) {
4056 newResource.setProperties(oldResource.getProperties());
4059 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
4061 if (overrideResource.isRight()) {
4062 ResponseFormat responseFormat = componentsUtils
4063 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
4064 .value()), newResource);
4065 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
4067 throwComponentException(responseFormat);
4069 updateCatalog(overrideResource.left()
4070 .value(), ChangeTypeEnum.LIFECYCLE);
4072 log.debug("Resource updated successfully!!!");
4073 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4074 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4075 ResourceVersionInfo.newBuilder()
4076 .state(oldResource.getLifecycleState()
4078 .version(oldResource.getVersion())
4081 resourcePair = new ImmutablePair<>(overrideResource.left()
4082 .value(), ActionStatus.OK);
4083 return resourcePair;
4085 if (resourcePair == null) {
4086 BeEcompErrorManager.getInstance()
4087 .logBeSystemError("Change LifecycleState - Certify");
4088 janusGraphDao.rollback();
4089 } else if (!inTransaction) {
4090 janusGraphDao.commit();
4093 log.debug("unlock resource {}", lockedResourceId);
4094 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4101 * Merge old resource with new. Keep old category and vendor name without
4104 * @param oldResource
4105 * @param newResource
4107 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4109 // keep old category and vendor name without change
4110 // merge the rest of the resource metadata
4111 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4112 newResource.setTags(oldResource.getTags());
4115 if (newResource.getDescription() == null) {
4116 newResource.setDescription(oldResource.getDescription());
4119 if (newResource.getVendorRelease() == null) {
4120 newResource.setVendorRelease(oldResource.getVendorRelease());
4123 if (newResource.getResourceVendorModelNumber() == null) {
4124 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4127 if (newResource.getContactId() == null) {
4128 newResource.setContactId(oldResource.getContactId());
4131 newResource.setCategories(oldResource.getCategories());
4132 if (newResource.getVendorName() == null) {
4133 newResource.setVendorName(oldResource.getVendorName());
4135 List<GroupDefinition>oldForUpdate = oldResource.getGroups();
4136 if(CollectionUtils.isNotEmpty(oldForUpdate)){
4137 List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
4139 groupForUpdate.stream().filter(group -> group.isVspOriginated())
4140 .forEach(group -> group.setName(group.getInvariantName()));
4142 newResource.setGroups(groupForUpdate);
4146 if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
4147 ResourceTypeEnum updatedResourceType = newResource.getResourceType();
4148 Component derivedFromResource = getParentComponent(newResource);
4149 if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
4150 Resource parentResource = (Resource) derivedFromResource;
4151 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
4152 parentResource.getResourceType() != updatedResourceType && oldResource.getResourceType() != updatedResourceType) {
4153 BeEcompErrorManager.getInstance()
4154 .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
4155 ErrorSeverity.ERROR);
4156 log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
4157 newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
4158 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
4165 private Component getParentComponent(Resource newResource) {
4166 String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
4167 Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
4168 if(latestByToscaResourceName.isRight()){
4169 BeEcompErrorManager.getInstance()
4170 .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
4171 log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
4172 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
4174 return latestByToscaResourceName.left().value();
4177 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
4178 boolean inTransaction, boolean needLock) {
4180 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
4182 return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4183 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
4185 .on(response -> failOnChangeState(response, user, oldResource, newResource));
4190 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
4191 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
4192 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4193 ResourceVersionInfo.newBuilder()
4194 .state(oldResource.getLifecycleState()
4196 .version(oldResource.getVersion())
4198 throw new ByResponseFormatComponentException(response);
4201 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
4202 boolean inTransaction, CsarInfo csarInfo) {
4204 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4205 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4206 validateLifecycleTypesCreate(user, resource, actionEnum);
4207 validateResourceType(user, resource, actionEnum);
4208 resource.setCreatorUserId(user.getUserId());
4209 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4210 resource.setContactId(resource.getContactId()
4212 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4213 String resourceSystemName;
4214 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4215 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4217 resourceSystemName = resource.getSystemName();
4219 resource.setToscaResourceName(CommonBeUtils
4220 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4223 // Generate invariant UUID - must be here and not in operation since it
4224 // should stay constant during clone
4226 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4227 resource.setInvariantUUID(invariantUUID);
4232 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4233 AuditingActionEnum actionEnum) {
4234 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4235 if (resource.getResourceType() == null) {
4236 log.debug("Invalid resource type for resource");
4237 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4238 eitherResult = Either.right(errorResponse);
4239 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4241 return eitherResult;
4244 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4245 AuditingActionEnum actionEnum) {
4246 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4247 if (resource.getInterfaces() != null && resource.getInterfaces()
4249 log.debug("validate interface lifecycle Types Exist");
4250 Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
4253 while (intItr.hasNext() && eitherResult.isLeft()) {
4254 InterfaceDefinition interfaceDefinition = intItr.next();
4255 String intType = interfaceDefinition.getUniqueId();
4256 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4257 .getInterface(intType);
4258 if (eitherCapTypeFound.isRight()) {
4259 if (eitherCapTypeFound.right()
4260 .value() == StorageOperationStatus.NOT_FOUND) {
4261 BeEcompErrorManager.getInstance()
4262 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
4263 "Interface", intType);
4264 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4265 intType, resource.getName());
4266 BeEcompErrorManager.getInstance()
4267 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4268 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
4273 ResponseFormat errorResponse = componentsUtils
4274 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4275 eitherResult = Either.right(errorResponse);
4276 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4281 return eitherResult;
4284 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4285 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4286 boolean inTransaction) {
4288 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4289 if (resource.getCapabilities() != null && resource.getCapabilities()
4291 log.debug("validate capability Types Exist - capabilities section");
4293 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
4296 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4297 eitherResult, typeEntry, inTransaction);
4298 if (eitherResult.isRight()) {
4299 return Either.right(eitherResult.right()
4305 if (resource.getRequirements() != null && resource.getRequirements()
4307 log.debug("validate capability Types Exist - requirements section");
4308 for (String type : resource.getRequirements()
4310 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4311 resource.getRequirements()
4313 actionEnum, eitherResult, type, inTransaction);
4314 if (eitherResult.isRight()) {
4315 return Either.right(eitherResult.right()
4321 return eitherResult;
4324 // @param typeObject- the object to which the validation is done
4325 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4326 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4327 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4328 boolean inTransaction) {
4329 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4330 .getCapabilityType(type, inTransaction);
4331 if (eitherCapTypeFound.isRight()) {
4332 if (eitherCapTypeFound.right()
4333 .value() == StorageOperationStatus.NOT_FOUND) {
4334 BeEcompErrorManager.getInstance()
4335 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4337 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4338 resource.getName());
4339 BeEcompErrorManager.getInstance()
4340 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4342 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
4345 ResponseFormat errorResponse = null;
4347 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4349 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4352 eitherResult = Either.right(errorResponse);
4353 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4355 return eitherResult;
4358 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4359 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4360 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4361 boolean inTransaction) {
4362 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4363 .getCapabilityType(typeEntry.getKey(), inTransaction);
4364 if (eitherCapTypeFound.isRight()) {
4365 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4366 BeEcompErrorManager.getInstance()
4367 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4368 typeEntry.getKey());
4369 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4370 typeEntry.getKey(), resource.getName());
4371 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4373 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4374 eitherCapTypeFound.right().value().name());
4375 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4376 typeEntry.getKey());
4377 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4378 return Either.right(errorResponse);
4380 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4381 if (capabilityTypeDefinition.getProperties() != null) {
4382 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4383 List<ComponentInstanceProperty> properties = capDef.getProperties();
4384 List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
4385 if (properties == null || properties.isEmpty()) {
4386 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4387 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4388 changedProperties.add(newProp);
4391 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4392 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4393 PropertyDefinition propFromDef = prop.getValue();
4394 boolean propFound = false;
4395 for (ComponentInstanceProperty cip : properties) {
4396 if (propFromDef.getName().equals(cip.getName())) {
4397 //merge property value and property description only, ignore other fields
4398 if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
4399 propFromDef.setDescription(cip.getDescription());
4401 propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
4402 if(cip.getValue() != null){
4403 propFromDef.setValue(cip.getValue());
4405 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4407 properties.remove(cip);
4412 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4415 if (!propsToAdd.isEmpty()) {
4416 changedProperties.addAll(propsToAdd);
4419 capDef.setProperties(changedProperties);
4422 return eitherResult;
4425 public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
4426 boolean isNormative, boolean inTransaction) {
4429 // lock new resource name in order to avoid creation resource with same
4431 Resource createdResource = null;
4432 if (!inTransaction) {
4433 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4435 if (lockResult.isRight()) {
4436 ResponseFormat responseFormat = lockResult.right().value();
4437 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4438 throw new ByResponseFormatComponentException(responseFormat);
4441 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4444 if (resource.deriveFromGeneric()) {
4445 handleResourceGenericType(resource);
4447 createdResource = createResourceTransaction(resource, user, isNormative);
4448 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4449 createdResource, actionEnum);
4450 ASDCKpiApi.countCreatedResourcesKPI();
4451 } catch (ComponentException e) {
4452 ResponseFormat responseFormat = e.getResponseFormat() == null
4453 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
4454 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4456 } catch (StorageException e) {
4457 ResponseFormat responseFormat = componentsUtils
4458 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
4459 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4462 if (!inTransaction) {
4463 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4464 NodeTypeEnum.Resource);
4467 return createdResource;
4470 private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
4471 // validate resource name uniqueness
4472 log.debug("validate resource name");
4473 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4474 resource.getName(), resource.getResourceType(), resource.getComponentType());
4475 if (eitherValidation.isRight()) {
4476 loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
4477 StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
4478 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4479 eitherValidation.right()
4481 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
4484 if (eitherValidation.left()
4486 log.debug("resource with name: {}, already exists", resource.getName());
4487 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
4488 StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
4489 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4490 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4493 log.debug("send resource {} to dao for create", resource.getName());
4495 createArtifactsPlaceHolderData(resource, user);
4498 log.debug("enrich resource with creator, version and state");
4499 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4500 resource.setVersion(INITIAL_VERSION);
4501 resource.setHighestVersion(true);
4502 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4503 resource.setAbstract(false);
4506 return toscaOperationFacade.createToscaComponent(resource)
4508 .on(r -> throwComponentExceptionByResource(r, resource));
4511 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
4512 ResponseFormat responseFormat = componentsUtils
4513 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
4514 throw new ByResponseFormatComponentException(responseFormat);
4517 private void createArtifactsPlaceHolderData(Resource resource, User user) {
4518 // create mandatory artifacts
4520 // TODO it must be removed after that artifact uniqueId creation will be
4521 // moved to ArtifactOperation
4523 setInformationalArtifactsPlaceHolder(resource, user);
4524 setDeploymentArtifactsPlaceHolder(resource, user);
4525 setToscaArtifactsPlaceHolders(resource, user);
4528 @SuppressWarnings("unchecked")
4530 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4531 Resource resource = (Resource) component;
4532 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4533 if (artifactMap == null) {
4534 artifactMap = new HashMap<>();
4536 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4538 .getDeploymentResourceArtifacts();
4539 if (deploymentResourceArtifacts != null) {
4540 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
4541 deploymentResourceArtifacts
4542 .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
4544 resource.setDeploymentArtifacts(artifactMap);
4547 private void processDeploymentResourceArtifacts(User user, Resource resource,
4548 Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
4549 Map<String, Object> artifactDetails = (Map<String, Object>) v;
4550 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4551 if (object != null) {
4552 List<String> artifactTypes = (List<String>) object;
4553 if (!artifactTypes.contains(resource.getResourceType()
4558 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
4560 if (artifactsBusinessLogic != null) {
4561 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4562 resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
4563 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
4564 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4569 @SuppressWarnings("unchecked")
4570 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4571 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4572 if (artifactMap == null) {
4573 artifactMap = new HashMap<>();
4575 String resourceUniqueId = resource.getUniqueId();
4576 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
4578 .getExcludeResourceCategory();
4579 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
4581 .getExcludeResourceType();
4582 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4584 .getInformationalResourceArtifacts();
4585 List<CategoryDefinition> categories = resource.getCategories();
4586 boolean isCreateArtifact = true;
4587 if (exludeResourceCategory != null) {
4588 String category = categories.get(0)
4590 isCreateArtifact = exludeResourceCategory.stream()
4591 .noneMatch(e -> e.equalsIgnoreCase(category));
4593 if (isCreateArtifact && exludeResourceType != null) {
4594 String resourceType = resource.getResourceType()
4596 isCreateArtifact = exludeResourceType.stream()
4597 .noneMatch(e -> e.equalsIgnoreCase(resourceType));
4599 if (informationalResourceArtifacts != null && isCreateArtifact) {
4600 Set<String> keys = informationalResourceArtifacts.keySet();
4601 for (String informationalResourceArtifactName : keys) {
4602 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4603 .get(informationalResourceArtifactName);
4604 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4605 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4606 ArtifactGroupTypeEnum.INFORMATIONAL);
4607 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4611 resource.setArtifacts(artifactMap);
4621 public ResponseFormat deleteResource(String resourceId, User user) {
4622 ResponseFormat responseFormat;
4623 validateUserExists(user);
4625 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4626 if (resourceStatus.isRight()) {
4627 log.debug("failed to get resource {}", resourceId);
4628 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4632 Resource resource = resourceStatus.left()
4635 StorageOperationStatus result = StorageOperationStatus.OK;
4636 lockComponent(resourceId, resource, "Mark resource to delete");
4639 result = markComponentToDelete(resource);
4640 if (result == StorageOperationStatus.OK) {
4641 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4643 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4644 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4646 return responseFormat;
4649 if (result == null || result != StorageOperationStatus.OK) {
4650 janusGraphDao.rollback();
4652 janusGraphDao.commit();
4654 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
4659 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
4660 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4661 validateUserExists(user);
4662 Resource resource = null;
4663 StorageOperationStatus result = StorageOperationStatus.OK;
4664 boolean failed = false;
4667 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
4668 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
4669 if (resourceStatus.isRight()) {
4670 log.debug("failed to get resource {} version {}", resourceName, version);
4671 return componentsUtils
4672 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4673 .value()), resourceName);
4676 resource = resourceStatus.left()
4680 janusGraphDao.commit();
4682 if (resource != null) {
4683 lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
4685 result = markComponentToDelete(resource);
4686 if (result != StorageOperationStatus.OK) {
4687 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4688 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4689 return responseFormat;
4691 }catch (ComponentException e){
4695 if (failed || result == null || result != StorageOperationStatus.OK) {
4696 janusGraphDao.rollback();
4698 janusGraphDao.commit();
4700 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
4703 return responseFormat;
4706 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
4709 validateUserExists(user);
4712 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
4713 if (storageStatus.isRight()) {
4714 log.debug("failed to get resource by id {}", resourceId);
4715 return Either.right(componentsUtils
4716 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
4717 .value()), resourceId));
4719 if (!(storageStatus.left()
4720 .value() instanceof Resource)) {
4721 return Either.right(componentsUtils.getResponseFormatByResource(
4722 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4724 return Either.left(storageStatus.left()
4729 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4732 validateUserExists(userId);
4734 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4735 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4736 if (getResource.isRight()) {
4737 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4738 return Either.right(componentsUtils
4739 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
4740 .value()), resourceName));
4742 return Either.left(getResource.left()
4747 * updateResourceMetadata
4750 * - modifier data (userId)
4751 * @param inTransaction
4753 * @param resourceIdToUpdate
4754 * - the resource identifier
4755 * @param newResource
4756 * @return Either<Resource , responseFormat>
4758 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
4759 User user, boolean inTransaction) {
4761 validateUserExists(user.getUserId());
4763 log.debug("Get resource with id {}", resourceIdToUpdate);
4764 boolean needToUnlock = false;
4767 if (currentResource == null) {
4768 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4769 .getToscaElement(resourceIdToUpdate);
4770 if (storageStatus.isRight()) {
4771 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4772 componentsUtils.convertFromStorageResponse(storageStatus.right()
4777 currentResource = storageStatus.left()
4780 // verify that resource is checked-out and the user is the last
4782 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4783 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4787 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4788 NodeTypeEnum.Resource);
4789 if (lockResult != StorageOperationStatus.OK) {
4790 BeEcompErrorManager.getInstance()
4791 .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
4792 resourceIdToUpdate);
4793 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4794 ResponseFormat responseFormat = componentsUtils
4795 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4796 throw new ByResponseFormatComponentException(responseFormat);
4799 needToUnlock = true;
4801 // critical section starts here
4802 // convert json to object
4804 // Update and updated resource must have a non-empty "derivedFrom"
4806 // This code is not called from import resources, because of root
4807 // VF "derivedFrom" should be null (or ignored)
4808 if (ModelConverter.isAtomicComponent(currentResource)) {
4809 validateDerivedFromNotEmpty(null, newResource, null);
4810 validateDerivedFromNotEmpty(null, currentResource, null);
4812 newResource.setDerivedFrom(null);
4815 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4816 user, currentResource, false, true);
4817 if (dataModelResponse.isRight()) {
4818 log.debug("failed to update resource metadata!!!");
4819 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4822 log.debug("Resource metadata updated successfully!!!");
4823 return dataModelResponse.left()
4826 } catch (ComponentException | StorageException e) {
4827 rollback(inTransaction, newResource, null, null);
4830 if (!inTransaction) {
4831 janusGraphDao.commit();
4834 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4839 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4840 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4841 updateVfModuleGroupsNames(currentResource, newResource);
4842 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4843 // Setting last updater and uniqueId
4844 newResource.setContactId(newResource.getContactId()
4846 newResource.setLastUpdaterUserId(user.getUserId());
4847 newResource.setUniqueId(resourceIdToUpdate);
4848 // Cannot set highest version through UI
4849 newResource.setHighestVersion(currentResource.isHighestVersion());
4850 newResource.setCreationDate(currentResource.getCreationDate());
4852 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4853 newResource, user.getUserId(), inTransaction);
4855 if (processUpdateOfDerivedFrom.isRight()) {
4856 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4857 return Either.right(processUpdateOfDerivedFrom.right()
4861 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4862 if (isNotEmpty(newResource.getGroups())) {
4863 for (GroupDefinition group : newResource.getGroups()) {
4864 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
4865 groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
4866 .getMetadataDataDefinition()
4867 .getUniqueId(), user, newResource.getComponentType(), group, true, false);
4871 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4872 .updateToscaElement(newResource);
4874 if (dataModelResponse.isRight()) {
4875 ResponseFormat responseFormat = componentsUtils
4876 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
4877 .value()), newResource);
4878 return Either.right(responseFormat);
4879 } else if (dataModelResponse.left()
4881 log.debug("No response from updateResource");
4882 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4884 return Either.left(dataModelResponse.left()
4888 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4889 if (currentResource.getGroups() != null && !currentResource.getName()
4890 .equals(newResource.getName())) {
4891 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4893 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4895 newResource.setGroups(updatedGroups);
4899 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4900 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4901 if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
4902 .equals(DEFAULT_GROUP_VF_MODULE)) {
4903 String prefix = updatedGroup.getName()
4904 .substring(0, replacePattern.length());
4905 String newGroupName = updatedGroup.getName()
4906 .replaceFirst(prefix, with);
4907 updatedGroup.setName(newGroupName);
4909 return updatedGroup;
4913 * validateResourceFieldsBeforeCreate
4916 * - modifier data (userId)
4918 private void validateResourceFieldsBeforeCreate(User user, Resource resource,
4919 AuditingActionEnum actionEnum, boolean inTransaction) {
4920 componentValidator.validate(user, resource, actionEnum);
4921 // validate category
4922 log.debug("validate category");
4923 validateCategory(user, resource, actionEnum, inTransaction);
4924 // validate vendor name & release & model number
4925 log.debug("validate vendor name");
4926 validateVendorName(user, resource, actionEnum);
4927 log.debug("validate vendor release");
4928 validateVendorReleaseName(user, resource, actionEnum);
4929 log.debug("validate resource vendor model number");
4930 validateResourceVendorModelNumber(user, resource, actionEnum);
4932 log.debug("validate cost");
4933 validateCost(resource);
4934 // validate licenseType
4935 log.debug("validate licenseType");
4936 validateLicenseType(user, resource, actionEnum);
4937 // validate template (derived from)
4938 log.debug("validate derived from");
4939 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4940 resource.setDerivedFrom(null);
4942 validateDerivedFromExist(user, resource, actionEnum);
4943 // warn about non-updatable fields
4944 checkComponentFieldsForOverrideAttempt(resource);
4945 String currentCreatorFullName = resource.getCreatorFullName();
4946 if (currentCreatorFullName != null) {
4947 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4950 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4951 if (currentLastUpdaterFullName != null) {
4952 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4955 Long currentLastUpdateDate = resource.getLastUpdateDate();
4956 if (currentLastUpdateDate != null) {
4957 log.debug("Resource last update date is automatically set and cannot be updated");
4960 Boolean currentAbstract = resource.isAbstract();
4961 if (currentAbstract != null) {
4962 log.debug("Resource abstract is automatically set and cannot be updated");
4967 * validateResourceFieldsBeforeUpdate
4969 * @param currentResource
4970 * - Resource object to validate
4973 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4974 boolean inTransaction, boolean isNested) {
4975 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4976 warnNonEditableFields(currentResource, updateInfoResource);
4979 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4980 String currentResourceVersion = currentResource.getVersion();
4981 String updatedResourceVersion = updateInfoResource.getVersion();
4983 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4984 log.debug("Resource version is automatically set and cannot be updated");
4987 String currentCreatorUserId = currentResource.getCreatorUserId();
4988 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4990 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4991 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4994 String currentCreatorFullName = currentResource.getCreatorFullName();
4995 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4997 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4998 log.debug("Resource Creator fullname is automatically set and cannot be updated");
5001 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
5002 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
5004 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
5005 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
5008 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
5009 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
5011 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
5012 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
5014 Long currentCreationDate = currentResource.getCreationDate();
5015 Long updatedCreationDate = updateInfoResource.getCreationDate();
5017 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
5018 log.debug("Resource Creation date is automatically set and cannot be updated");
5021 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
5022 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
5024 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
5025 log.debug("Resource last update date is automatically set and cannot be updated");
5028 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
5029 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
5031 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
5032 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
5035 Boolean currentAbstract = currentResource.isAbstract();
5036 Boolean updatedAbstract = updateInfoResource.isAbstract();
5038 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
5039 log.debug("Resource abstract is automatically set and cannot be updated");
5042 Boolean currentHighestVersion = currentResource.isHighestVersion();
5043 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
5045 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
5046 log.debug("Resource highest version is automatically set and cannot be updated");
5049 String currentUuid = currentResource.getUUID();
5050 String updatedUuid = updateInfoResource.getUUID();
5052 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
5053 log.debug("Resource UUID is automatically set and cannot be updated");
5056 log.debug("Resource Type cannot be updated");
5057 String currentInvariantUuid = currentResource.getInvariantUUID();
5058 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
5060 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5061 log.debug("Resource invariant UUID is automatically set and cannot be updated");
5062 updateInfoResource.setInvariantUUID(currentInvariantUuid);
5066 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
5068 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5069 log.debug("validate resource name before update");
5070 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
5071 log.debug("validate description before update");
5072 componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
5073 log.debug("validate icon before update");
5074 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5075 log.debug("validate tags before update");
5076 componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
5077 log.debug("validate vendor name before update");
5078 validateVendorName(null, updateInfoResource, null);
5079 log.debug("validate resource vendor model number before update");
5080 validateResourceVendorModelNumber(currentResource, updateInfoResource);
5081 log.debug("validate vendor release before update");
5082 validateVendorReleaseName(null, updateInfoResource, null);
5083 log.debug("validate contact info before update");
5084 componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
5085 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
5086 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5087 log.debug("validate category before update");
5088 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5091 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5092 String resourceNameUpdated = updateInfoResource.getName();
5093 String resourceNameCurrent = currentResource.getName();
5094 if (resourceNameCurrent.equals(resourceNameUpdated)) {
5097 // In case of CVFC type we should support the case of old VF with CVFC
5098 // instances that were created without the "Cvfc" suffix
5099 return currentResource.getResourceType() == ResourceTypeEnum.CVFC
5100 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5103 private String addCvfcSuffixToResourceName(String resourceName) {
5104 return resourceName + "Cvfc";
5107 private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
5109 String resourceNameUpdated = updateInfoResource.getName();
5110 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5111 if (isNested || !hasBeenCertified) {
5112 componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
5113 validateResourceNameUniqueness(updateInfoResource);
5114 currentResource.setName(resourceNameUpdated);
5115 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5116 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5119 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5120 resourceNameUpdated);
5121 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5126 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5127 String iconUpdated = updateInfoResource.getIcon();
5128 String iconCurrent = currentResource.getIcon();
5129 if (!iconCurrent.equals(iconUpdated)) {
5130 if (!hasBeenCertified) {
5131 componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
5133 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5134 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5139 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
5140 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5141 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5142 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5143 validateResourceVendorModelNumber(null, updateInfoResource, null);
5147 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5148 boolean hasBeenCertified, boolean inTransaction) {
5149 validateCategory(null, updateInfoResource, null, inTransaction);
5150 if (hasBeenCertified) {
5151 CategoryDefinition currentCategory = currentResource.getCategories()
5153 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
5155 CategoryDefinition updateCategory = updateInfoResource.getCategories()
5157 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
5159 if (!currentCategory.getName()
5160 .equals(updateCategory.getName())
5161 || !currentSubCategory.getName()
5162 .equals(updtaeSubCategory.getName())) {
5163 log.info("Category {} cannot be updated once the resource has been certified once.",
5164 currentResource.getCategories());
5165 ResponseFormat errorResponse = componentsUtils
5166 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5167 return Either.right(errorResponse);
5170 return Either.left(true);
5173 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5174 Resource updateInfoResource, boolean hasBeenCertified) {
5176 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5177 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5178 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5179 || updatedDerivedFrom.isEmpty()) {
5180 log.trace("Update normative types");
5181 return Either.left(true);
5184 String derivedFromCurrent = currentDerivedFrom.get(0);
5185 String derivedFromUpdated = updatedDerivedFrom.get(0);
5187 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5188 if (!hasBeenCertified) {
5189 validateDerivedFromExist(null, updateInfoResource, null);
5191 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5192 currentResource, updateInfoResource, null);
5194 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5196 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5197 return validateDerivedFromExtending;
5201 // For derived from, we must know whether it was actually changed,
5202 // otherwise we must do no action.
5203 // Due to changes it inflicts on data model (remove artifacts,
5204 // properties...), it's not like a flat field which can be
5205 // overwritten if not changed.
5206 // So we must indicate that derived from is not changed
5207 updateInfoResource.setDerivedFrom(null);
5209 return Either.left(true);
5212 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5213 Resource updateInfoResource, boolean hasBeenCertified) {
5215 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5216 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5217 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5218 || updatedDerivedFrom.isEmpty()) {
5219 log.trace("Update normative types");
5220 return Either.left(true);
5223 String derivedFromCurrent = currentDerivedFrom.get(0);
5224 String derivedFromUpdated = updatedDerivedFrom.get(0);
5226 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5227 if (!hasBeenCertified) {
5228 validateDerivedFromExist(null, updateInfoResource, null);
5230 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5231 currentResource, updateInfoResource, null);
5233 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5235 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5236 return validateDerivedFromExtending;
5240 return Either.left(true);
5243 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5244 if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
5248 String templateName = resource.getDerivedFrom()
5250 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5251 .validateToscaResourceNameExists(templateName);
5252 if (dataModelResponse.isRight()) {
5253 StorageOperationStatus storageStatus = dataModelResponse.right()
5255 BeEcompErrorManager.getInstance()
5256 .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5257 log.debug("request to data model failed with error: {}", storageStatus);
5258 ResponseFormat responseFormat = componentsUtils
5259 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5260 log.trace("audit before sending response");
5261 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5262 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
5263 } else if (!dataModelResponse.left()
5265 log.info("resource template with name: {}, does not exists", templateName);
5266 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5267 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5268 throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5272 // Tal G for extending inheritance US815447
5273 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5274 Resource updateInfoResource, AuditingActionEnum actionEnum) {
5275 String currentTemplateName = currentResource.getDerivedFrom()
5277 String updatedTemplateName = updateInfoResource.getDerivedFrom()
5280 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5281 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5282 if (dataModelResponse.isRight()) {
5283 StorageOperationStatus storageStatus = dataModelResponse.right()
5285 BeEcompErrorManager.getInstance()
5286 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5287 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5288 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5289 log.trace("audit before sending response");
5290 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5291 return Either.right(responseFormat);
5294 if (!dataModelResponse.left()
5296 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5297 currentTemplateName);
5298 ResponseFormat responseFormat = componentsUtils
5299 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5300 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5302 return Either.right(responseFormat);
5305 return Either.left(true);
5308 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5309 log.debug("validate resource derivedFrom field");
5310 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
5312 || (resource.getDerivedFrom()
5314 || (resource.getDerivedFrom()
5318 log.info("derived from (template) field is missing for the resource");
5319 ResponseFormat responseFormat = componentsUtils
5320 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5321 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5323 throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5327 private void validateResourceNameUniqueness(Resource resource) {
5329 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5330 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5331 resource.getComponentType());
5332 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
5334 log.debug("resource with name: {}, already exists", resource.getName());
5335 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
5336 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5337 } else if (resourceOperationResponse.isRight()) {
5338 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5339 throw new StorageException(resourceOperationResponse.right()
5344 private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5346 List<CategoryDefinition> categories = resource.getCategories();
5347 if (CollectionUtils.isEmpty(categories)) {
5348 log.debug(CATEGORY_IS_EMPTY);
5349 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5350 ComponentTypeEnum.RESOURCE.getValue());
5351 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5352 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5353 ComponentTypeEnum.RESOURCE.getValue());
5355 if (categories.size() > 1) {
5356 log.debug("Must be only one category for resource");
5357 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
5358 ComponentTypeEnum.RESOURCE.getValue());
5360 CategoryDefinition category = categories.get(0);
5361 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5362 if (CollectionUtils.isEmpty(subcategories)) {
5363 log.debug("Missinig subcategory for resource");
5364 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5366 if (subcategories.size() > 1) {
5367 log.debug("Must be only one sub category for resource");
5368 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5371 SubCategoryDefinition subcategory = subcategories.get(0);
5373 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5374 log.debug(CATEGORY_IS_EMPTY);
5375 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5376 ComponentTypeEnum.RESOURCE.getValue());
5377 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5378 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5379 ComponentTypeEnum.RESOURCE.getValue());
5381 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5382 log.debug(CATEGORY_IS_EMPTY);
5383 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5384 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5385 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5386 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
5387 ComponentTypeEnum.RESOURCE.getValue());
5390 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
5393 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
5394 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5395 ResponseFormat responseFormat;
5396 if (category != null && subcategory != null) {
5397 log.debug("validating resource category {} against valid categories list", category);
5398 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5399 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5400 if (categories.isRight()) {
5401 log.debug("failed to retrieve resource categories from JanusGraph");
5402 responseFormat = componentsUtils.getResponseFormat(categories.right()
5404 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5405 throw new ByActionStatusComponentException(categories.right()
5408 List<CategoryDefinition> categoryList = categories.left()
5410 Optional<CategoryDefinition> foundCategory = categoryList.stream()
5411 .filter(cat -> cat.getName()
5412 .equals(category.getName()))
5414 if (!foundCategory.isPresent()) {
5415 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5416 category, categoryList);
5417 failOnInvalidCategory(user, resource, actionEnum);
5419 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
5422 .filter(subcat -> subcat.getName()
5423 .equals(subcategory.getName()))
5425 if (!foundSubcategory.isPresent()) {
5427 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5428 subcategory, foundCategory.get()
5429 .getSubcategories());
5430 failOnInvalidCategory(user, resource, actionEnum);
5435 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
5436 ResponseFormat responseFormat;
5437 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5438 ComponentTypeEnum.RESOURCE.getValue());
5439 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5440 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5443 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
5444 String vendorRelease = resource.getVendorRelease();
5445 log.debug("validate vendor relese name");
5446 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5447 log.info("vendor relese name is missing.");
5448 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5449 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5450 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
5453 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
5456 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
5457 AuditingActionEnum actionEnum) {
5458 if (vendorRelease != null) {
5459 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
5460 log.info("vendor release exceds limit.");
5461 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5462 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5463 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5464 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
5465 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5468 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
5469 log.info("vendor release is not valid.");
5470 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
5471 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5472 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
5477 private void validateVendorName(User user, Resource resource,
5478 AuditingActionEnum actionEnum) {
5479 String vendorName = resource.getVendorName();
5480 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
5481 log.info("vendor name is missing.");
5482 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
5483 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5484 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
5486 validateVendorName(vendorName, user, resource, actionEnum);
5489 private void validateVendorName(String vendorName, User user, Resource resource,
5490 AuditingActionEnum actionEnum) {
5491 if (vendorName != null) {
5492 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
5493 log.info("vendor name exceds limit.");
5494 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5495 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5496 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5497 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5498 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5501 if (!ValidationUtils.validateVendorName(vendorName)) {
5502 log.info("vendor name is not valid.");
5503 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
5504 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5505 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME, vendorName);
5510 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
5511 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
5512 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
5513 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
5514 log.info("resource vendor model number exceeds limit.");
5515 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5516 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5517 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5518 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5519 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5520 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5522 // resource vendor model number is currently validated as vendor
5524 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
5525 log.info("resource vendor model number is not valid.");
5526 ResponseFormat errorResponse = componentsUtils
5527 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5528 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5529 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5535 private void validateCost(Resource resource) {
5536 String cost = resource.getCost();
5538 if (!ValidationUtils.validateCost(cost)) {
5539 log.debug("resource cost is invalid.");
5540 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5545 private void validateLicenseType(User user, Resource resource,
5546 AuditingActionEnum actionEnum) {
5547 log.debug("validate licenseType");
5548 String licenseType = resource.getLicenseType();
5549 if (licenseType != null) {
5550 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
5552 if (!licenseTypes.contains(licenseType)) {
5553 log.debug("License type {} isn't configured", licenseType);
5554 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5555 if (actionEnum != null) {
5556 // In update case, no audit is required
5557 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5559 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5564 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
5565 Resource updatedResource, String userId, boolean inTransaction) {
5566 if (updatedResource.getDerivedFrom() != null) {
5567 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
5568 log.debug("1. Removing interface artifacts from graph");
5569 // Remove all interface artifacts of resource
5570 String resourceId = updatedResource.getUniqueId();
5571 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
5573 if (interfaces != null) {
5574 Collection<InterfaceDefinition> values = interfaces.values();
5575 for (InterfaceDefinition interfaceDefinition : values) {
5576 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
5578 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
5579 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
5580 if (operations != null) {
5581 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
5582 Operation operation = operationEntry.getValue();
5583 ArtifactDefinition implementation = operation.getImplementationArtifact();
5584 if (implementation != null) {
5585 String uniqueId = implementation.getUniqueId();
5586 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
5587 uniqueId, operationEntry.getKey(), interfaceType);
5588 // only thing that transacts and locks here
5589 Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface =
5590 artifactsBusinessLogic.deleteArtifactByInterface(resourceId, userId, uniqueId, true);
5591 if (deleteArtifactByInterface.isRight()) {
5592 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
5593 if (!inTransaction) {
5594 janusGraphDao.rollback();
5596 return Either.right(deleteArtifactByInterface.right()
5600 log.trace("No implementation found for operation {} - nothing to delete",
5601 operationEntry.getKey());
5605 log.trace("No operations found for interface type {}", interfaceType);
5609 log.debug("2. Removing properties");
5610 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
5611 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
5613 if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
5614 log.debug("Failed to remove all properties of resource");
5615 if (!inTransaction) {
5616 janusGraphDao.rollback();
5618 return Either.right(componentsUtils
5619 .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
5624 log.debug("Derived from wasn't changed during update");
5627 if (inTransaction) {
5628 return Either.left(true);
5630 janusGraphDao.commit();
5631 return Either.left(true);
5635 /**** Auditing *******************/
5637 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
5638 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
5639 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
5641 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
5643 return webApplicationContext.getBean(class1);
5646 public ICapabilityTypeOperation getCapabilityTypeOperation() {
5647 return capabilityTypeOperation;
5651 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
5652 this.capabilityTypeOperation = capabilityTypeOperation;
5655 public Boolean validatePropertiesDefaultValues(Resource resource) {
5656 log.debug("validate resource properties default values");
5657 List<PropertyDefinition> properties = resource.getProperties();
5658 if (properties != null) {
5659 iterateOverProperties(properties);
5664 public void iterateOverProperties(List<PropertyDefinition> properties) {
5666 String innerType = null;
5667 for (PropertyDefinition property : properties) {
5668 if (!propertyOperation.isPropertyTypeValid(property)) {
5669 log.info("Invalid type for property {}", property);
5670 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
5671 property.getType(), property.getName());
5674 Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
5675 type = property.getType();
5677 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5678 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
5679 if (responseFormat != null) {
5683 validateDefaultPropertyValue(property, allDataTypes, type, innerType);
5687 private void validateDefaultPropertyValue(PropertyDefinition property,
5688 Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
5689 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
5690 log.info("Invalid default value for property {}", property);
5691 ResponseFormat responseFormat;
5692 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5693 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
5694 property.getName(), type, innerType, property.getDefaultValue());
5696 throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
5697 property.getName(), type, property.getDefaultValue());
5701 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
5702 Map<String, DataTypeDefinition> allDataTypes) {
5703 ResponseFormat responseFormat = null;
5704 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
5706 innerType = propertyInnerTypeValid.getLeft();
5707 if (!propertyInnerTypeValid.getRight()
5709 log.info("Invalid inner type for property {}", property);
5710 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
5711 property.getName());
5713 return responseFormat;
5717 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
5718 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
5722 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
5723 return componentInstanceBusinessLogic;
5726 private String getComponentTypeForResponse(Component component) {
5727 String componentTypeForResponse = "SERVICE";
5728 if (component instanceof Resource) {
5729 componentTypeForResponse = ((Resource) component).getResourceType()
5732 return componentTypeForResponse;
5735 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
5738 validateUserExists(user);
5740 // get resource from csar uuid
5741 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
5742 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
5743 if (either.isRight()) {
5744 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
5746 return Either.right(resp);
5749 return Either.left(either.left()
5754 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5755 String componentId, String userId) {
5759 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
5760 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5761 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5763 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5764 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
5765 defaultCapabilities, validCapabilitiesMap));
5766 return validCapabilitiesMap;
5769 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
5770 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5771 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
5772 String capabilityType = capabilities.get(0)
5774 if (defaultCapabilities.containsKey(capabilityType)) {
5775 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5776 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5777 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5778 validCapabilityList.add(defaultCapability);
5779 validCapabilitiesMap.put(key, validCapabilityList);
5781 throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
5785 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
5786 CapabilityDefinition defaultCapability) {
5787 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
5788 .getProperties())) {
5789 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5790 defaultCapability.getName(), resourceId);
5791 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
5792 defaultCapability.getName());
5793 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
5794 } else if (isNotEmpty(capabilities.get(0)
5795 .getProperties())) {
5796 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5800 private CapabilityDefinition getCapability(String resourceId,
5801 Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5802 CapabilityDefinition defaultCapability;
5803 if (isNotEmpty(defaultCapabilities.get(capabilityType)
5805 .getProperties())) {
5806 defaultCapability = defaultCapabilities.get(capabilityType)
5809 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5810 .getToscaFullElement(resourceId);
5811 if (getFullComponentRes.isRight()) {
5812 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
5814 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
5816 defaultCapability = getFullComponentRes.left()
5819 .get(capabilityType)
5822 return defaultCapability;
5825 private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
5826 UploadCapInfo uploadedCapability) {
5827 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5828 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
5830 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5831 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5832 for (UploadPropInfo property : uploadedProperties) {
5833 String propertyName = property.getName()
5835 String propertyType = property.getType();
5836 ComponentInstanceProperty validProperty;
5837 if (defaultProperties.containsKey(propertyName)
5838 && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5839 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
5841 validProperty = new ComponentInstanceProperty();
5842 validProperty.setName(propertyName);
5843 if (property.getValue() != null) {
5844 validProperty.setValue(property.getValue()
5847 validProperty.setDescription(property.getDescription());
5848 validProperty.setPassword(property.isPassword());
5849 validProperties.add(validProperty);
5851 defaultCapability.setProperties(validProperties);
5854 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
5855 String propertyType) {
5856 return propertyType != null && !defaultProperties.get(propertyName)
5858 .equals(propertyType);
5861 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5862 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5863 Resource resource, User user) {
5865 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5866 ArtifactOperationEnum.class);
5867 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5868 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5869 .left(nodeTypeArtifactsToHandle);
5871 // add all found Csar artifacts to list to upload
5872 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5873 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5874 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5875 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5876 ArtifactDefinition foundArtifact;
5878 if (!existingArtifactsToHandle.isEmpty()) {
5879 foundArtifact = existingArtifactsToHandle.stream()
5880 .filter(a -> a.getArtifactName()
5881 .equals(currNewArtifact.getArtifactName()))
5884 if (foundArtifact != null) {
5885 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
5886 if (!foundArtifact.getArtifactChecksum()
5887 .equals(currNewArtifact.getArtifactChecksum())) {
5888 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5889 // if current artifact already exists, but has
5890 // different content, add him to the list to
5892 artifactsToUpdate.add(currNewArtifact);
5894 // remove found artifact from the list of existing
5895 // artifacts to handle, because it was already
5897 existingArtifactsToHandle.remove(foundArtifact);
5898 // and remove found artifact from the list to
5899 // upload, because it should either be updated or be
5901 artifactsToUpload.remove(currNewArtifact);
5903 log.debug("Can't upload two artifact with the same name {}.",
5904 currNewArtifact.getArtifactName());
5905 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
5906 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5907 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
5908 foundArtifact.getArtifactType());
5909 AuditingActionEnum auditingAction = artifactsBusinessLogic
5910 .detectAuditingType(new ArtifactOperationInfo(false, false,
5911 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5912 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5913 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5914 resource.getComponentType(), null);
5915 responseWrapper.setInnerElement(responseFormat);
5921 if (responseWrapper.isEmpty()) {
5922 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5923 if (currArtifact.getIsFromCsar()) {
5924 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5925 currArtifact.getArtifactType(),
5926 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5927 currArtifact.getIsFromCsar()));
5929 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5930 currArtifact.getArtifactType(),
5931 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5932 currArtifact.getIsFromCsar()));
5937 if (responseWrapper.isEmpty()) {
5938 if (!artifactsToUpload.isEmpty()) {
5939 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5941 if (!artifactsToUpdate.isEmpty()) {
5942 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5944 if (!artifactsToDelete.isEmpty()) {
5945 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5948 if (!responseWrapper.isEmpty()) {
5949 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5951 } catch (Exception e) {
5952 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5953 responseWrapper.setInnerElement(responseFormat);
5954 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5956 return nodeTypeArtifactsToHandleRes;
5959 ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
5960 final String vfResourceName,
5961 final String nodeTypeFullName) {
5963 String actualVfName;
5964 if (ResourceTypeEnum.CVFC.name()
5965 .equals(nodeResourceType)) {
5966 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5967 actualType = ResourceTypeEnum.VFC.name();
5969 actualVfName = vfResourceName;
5970 actualType = nodeResourceType;
5972 String nameWithouNamespacePrefix;
5974 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
5975 log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
5976 + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName,
5977 nodeTypeFullName, actualType, vfResourceName);
5978 final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
5980 if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
5981 nameWithouNamespacePrefix = nodeTypeFullName;
5983 nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
5985 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5987 if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
5988 actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
5990 actualName = "." + nameWithouNamespacePrefix;
5993 if (actualName.startsWith(Constants.ABSTRACT)) {
5994 toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
5995 .append(ValidationUtils.convertToSystemName(actualVfName));
5997 toscaResourceName.append(actualType.toLowerCase()).append('.')
5998 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
6000 final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
6001 final String[] actualNames = actualName.split("\\.");
6002 if (actualNames.length < 3) {
6003 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
6004 previousToscaResourceName.append(actualName).toString());
6006 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
6007 previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
6008 .toLowerCase()).toString());
6009 } catch (final Exception e) {
6010 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
6011 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
6016 * Extracts a Node Type Name prefix from the given Node Type Name.
6018 * @param fullName Node Type Name
6019 * @return Node Type Name Prefix
6021 private String getNodeTypeNamePrefix(final String fullName) {
6022 String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
6023 final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
6024 log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
6025 final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
6026 if (validNameSpace.isPresent()) {
6027 tempPrefix = validNameSpace.get();
6029 log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
6034 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
6035 List<String> dataParamsToReturn) {
6037 ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
6038 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToReturn);
6040 if (resourceResultEither.isRight()) {
6041 if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
6042 log.debug("Failed to found resource with id {} ", resourceId);
6044 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
6047 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
6048 return Either.right(componentsUtils
6049 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
6053 Resource resource = resourceResultEither.left().value();
6054 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
6055 ListUtils.emptyIfNull(resource.getInputs())
6056 .forEach(input -> input.setConstraints(setInputConstraint(input)));
6059 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
6060 dataParamsToReturn);
6061 return Either.left(dataTransfer);
6065 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
6066 Resource resource = (Resource) clonedComponent;
6067 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
6068 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
6069 .shouldUpgradeToLatestDerived(resource);
6070 if (shouldUpgradeToLatestDerived.isRight()) {
6071 return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
6074 return Either.left(shouldUpgradeToLatestDerived.left()
6077 return super.shouldUpgradeToLatestDerived(clonedComponent);