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.EnumMap;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.ListIterator;
46 import java.util.Map.Entry;
47 import java.util.Optional;
49 import java.util.function.Function;
50 import java.util.regex.Pattern;
51 import java.util.stream.Collectors;
52 import javax.servlet.ServletContext;
53 import org.apache.commons.codec.binary.Base64;
54 import org.apache.commons.collections.CollectionUtils;
55 import org.apache.commons.collections.MapUtils;
56 import org.apache.commons.collections4.ListUtils;
57 import org.apache.commons.lang.StringUtils;
58 import org.apache.commons.lang3.tuple.ImmutablePair;
59 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
60 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
61 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
62 import org.openecomp.sdc.be.components.csar.CsarInfo;
63 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
64 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
65 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
66 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
67 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
68 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
69 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
70 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
71 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
72 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
73 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
74 import org.openecomp.sdc.be.components.merge.TopologyComparator;
75 import org.openecomp.sdc.be.components.merge.property.PropertyDataValueMergeBusinessLogic;
76 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
77 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
78 import org.openecomp.sdc.be.components.property.PropertyConstraintsUtils;
79 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
80 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
81 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
82 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
83 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
84 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
85 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
86 import org.openecomp.sdc.be.config.BeEcompErrorManager;
87 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
88 import org.openecomp.sdc.be.config.ConfigurationManager;
89 import org.openecomp.sdc.be.dao.api.ActionStatus;
90 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
91 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
92 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
93 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
94 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
95 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
96 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
97 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
98 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
99 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
100 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
101 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
102 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
103 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
104 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
105 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
106 import org.openecomp.sdc.be.impl.ComponentsUtils;
107 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
108 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
109 import org.openecomp.sdc.be.model.ArtifactDefinition;
110 import org.openecomp.sdc.be.model.CapabilityDefinition;
111 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
112 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
113 import org.openecomp.sdc.be.model.Component;
114 import org.openecomp.sdc.be.model.ComponentInstance;
115 import org.openecomp.sdc.be.model.ComponentInstanceInput;
116 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
117 import org.openecomp.sdc.be.model.ComponentParametersView;
118 import org.openecomp.sdc.be.model.DataTypeDefinition;
119 import org.openecomp.sdc.be.model.GroupDefinition;
120 import org.openecomp.sdc.be.model.InputDefinition;
121 import org.openecomp.sdc.be.model.InterfaceDefinition;
122 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
123 import org.openecomp.sdc.be.model.LifecycleStateEnum;
124 import org.openecomp.sdc.be.model.NodeTypeInfo;
125 import org.openecomp.sdc.be.model.Operation;
126 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
127 import org.openecomp.sdc.be.model.PolicyDefinition;
128 import org.openecomp.sdc.be.model.PropertyDefinition;
129 import org.openecomp.sdc.be.model.RelationshipImpl;
130 import org.openecomp.sdc.be.model.RelationshipInfo;
131 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
132 import org.openecomp.sdc.be.model.RequirementDefinition;
133 import org.openecomp.sdc.be.model.Resource;
134 import org.openecomp.sdc.be.model.UploadArtifactInfo;
135 import org.openecomp.sdc.be.model.UploadCapInfo;
136 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
137 import org.openecomp.sdc.be.model.UploadInfo;
138 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
139 import org.openecomp.sdc.be.model.UploadPropInfo;
140 import org.openecomp.sdc.be.model.UploadReqInfo;
141 import org.openecomp.sdc.be.model.UploadResourceInfo;
142 import org.openecomp.sdc.be.model.User;
143 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
144 import org.openecomp.sdc.be.model.category.CategoryDefinition;
145 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
146 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
147 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
148 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
149 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
150 import org.openecomp.sdc.be.model.operations.StorageException;
151 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
152 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
153 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
154 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
155 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
156 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
157 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
158 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
159 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
160 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
161 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
162 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
163 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
164 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
165 import org.openecomp.sdc.be.tosca.CsarUtils;
166 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
167 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
168 import org.openecomp.sdc.be.user.UserBusinessLogic;
169 import org.openecomp.sdc.be.utils.CommonBeUtils;
170 import org.openecomp.sdc.be.utils.TypeUtils;
171 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
172 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
173 import org.openecomp.sdc.common.api.Constants;
174 import org.openecomp.sdc.common.datastructure.Wrapper;
175 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
176 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
177 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
178 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
179 import org.openecomp.sdc.common.log.enums.StatusCode;
180 import org.openecomp.sdc.common.log.wrappers.Logger;
181 import org.openecomp.sdc.common.util.GeneralUtility;
182 import org.openecomp.sdc.common.util.ValidationUtils;
183 import org.openecomp.sdc.exception.ResponseFormat;
184 import org.springframework.beans.factory.annotation.Autowired;
185 import org.springframework.context.annotation.Lazy;
186 import org.springframework.web.context.WebApplicationContext;
187 import org.yaml.snakeyaml.DumperOptions;
188 import org.yaml.snakeyaml.Yaml;
190 @org.springframework.stereotype.Component("resourceBusinessLogic")
191 public class ResourceBusinessLogic extends ComponentBusinessLogic {
193 private static final String DELETE_RESOURCE = "Delete Resource";
194 private static final String IN_RESOURCE = " in resource {} ";
195 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
196 public static final String INITIAL_VERSION = "0.1";
197 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
198 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
199 private static final String CREATE_RESOURCE = "Create Resource";
200 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
201 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
202 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
203 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
204 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
205 public LoggerSupportability loggerSupportability=LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
208 private IInterfaceLifecycleOperation interfaceTypeOperation;
209 private LifecycleBusinessLogic lifecycleBusinessLogic;
211 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
212 private final ResourceImportManager resourceImportManager;
213 private final InputsBusinessLogic inputsBusinessLogic;
214 private final CompositionBusinessLogic compositionBusinessLogic;
215 private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
216 private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
217 private final MergeInstanceUtils mergeInstanceUtils;
218 private final UiComponentDataConverter uiComponentDataConverter;
219 private final CsarBusinessLogic csarBusinessLogic;
220 private final PropertyBusinessLogic propertyBusinessLogic;
221 private final PolicyBusinessLogic policyBusinessLogic;
224 public ResourceBusinessLogic(IElementOperation elementDao,
225 IGroupOperation groupOperation,
226 IGroupInstanceOperation groupInstanceOperation,
227 IGroupTypeOperation groupTypeOperation,
228 GroupBusinessLogic groupBusinessLogic,
229 InterfaceOperation interfaceOperation,
230 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
231 ArtifactsBusinessLogic artifactsBusinessLogic,
232 ComponentInstanceBusinessLogic componentInstanceBusinessLogic, @Lazy ResourceImportManager resourceImportManager,
233 InputsBusinessLogic inputsBusinessLogic, CompositionBusinessLogic compositionBusinessLogic,
234 ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
235 CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic, MergeInstanceUtils mergeInstanceUtils,
236 UiComponentDataConverter uiComponentDataConverter, CsarBusinessLogic csarBusinessLogic,
237 ArtifactsOperations artifactToscaOperation, PropertyBusinessLogic propertyBusinessLogic,
238 ComponentContactIdValidator componentContactIdValidator,
239 ComponentNameValidator componentNameValidator, ComponentTagsValidator componentTagsValidator,
240 ComponentValidator componentValidator,
241 ComponentIconValidator componentIconValidator,
242 ComponentProjectCodeValidator componentProjectCodeValidator,
243 ComponentDescriptionValidator componentDescriptionValidator, PolicyBusinessLogic policyBusinessLogic) {
244 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
245 interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation,
246 componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
247 componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
248 this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
249 this.resourceImportManager = resourceImportManager;
250 this.inputsBusinessLogic = inputsBusinessLogic;
251 this.compositionBusinessLogic = compositionBusinessLogic;
252 this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
253 this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
254 this.mergeInstanceUtils = mergeInstanceUtils;
255 this.uiComponentDataConverter = uiComponentDataConverter;
256 this.csarBusinessLogic = csarBusinessLogic;
257 this.propertyBusinessLogic = propertyBusinessLogic;
258 this.policyBusinessLogic = policyBusinessLogic;
262 private ICapabilityTypeOperation capabilityTypeOperation;
265 private TopologyComparator topologyComparator;
268 private ComponentValidator componentValidator;
271 private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
274 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
276 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
277 return lifecycleBusinessLogic;
281 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
282 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
286 protected void setComponentValidator(ComponentValidator componentValidator) {
287 this.componentValidator = componentValidator;
290 public IElementOperation getElementDao() {
294 public void setElementDao(IElementOperation elementDao) {
295 this.elementDao = elementDao;
298 public UserBusinessLogic getUserAdmin() {
299 return this.userAdmin;
303 public void setUserAdmin(UserBusinessLogic userAdmin) {
304 this.userAdmin = userAdmin;
307 public ComponentsUtils getComponentsUtils() {
308 return this.componentsUtils;
312 public void setComponentsUtils(ComponentsUtils componentsUtils) {
313 this.componentsUtils = componentsUtils;
316 public ArtifactsBusinessLogic getArtifactsManager() {
317 return artifactsBusinessLogic;
320 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
321 this.artifactsBusinessLogic = artifactsManager;
324 public ApplicationDataTypeCache getApplicationDataTypeCache() {
325 return applicationDataTypeCache;
329 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
330 this.applicationDataTypeCache = applicationDataTypeCache;
334 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
335 this.interfaceTypeOperation = interfaceTypeOperation;
339 * the method returns a list of all the resources that are certified, the
340 * returned resources are only abstract or only none abstract according to
348 public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter,
350 User user = validateUserExists(userId);
351 Boolean isHighest = null;
352 switch (highestFilter) {
358 case NON_HIGHEST_ONLY:
364 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
365 .getAllCertifiedResources(getAbstract, isHighest);
367 if (getResponse.isRight()) {
368 throw new StorageException(getResponse.right()
372 return getResponse.left()
376 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
377 ResourceTypeEnum resourceTypeEnum, String userId) {
379 validateUserExists(userId);
381 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
382 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
384 janusGraphDao.commit();
386 if (dataModelResponse.isLeft()) {
387 Map<String, Boolean> result = new HashMap<>();
388 result.put("isValid", dataModelResponse.left()
390 log.debug("validation was successfully performed.");
391 return Either.left(result);
394 ResponseFormat responseFormat = componentsUtils
395 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
398 return Either.right(responseFormat);
401 public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user,
402 Map<String, byte[]> csarUIPayload, String payloadName) {
403 validateResourceBeforeCreate(resource, user, false);
404 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
405 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId());
406 if (StringUtils.isNotEmpty(csarUUID)) {
407 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
408 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
410 Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
411 return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left()
412 .map(r -> (Resource) r)
417 final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
418 return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left()
419 .map(r -> (Resource) r)
424 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
425 String payloadName, String resourceUniqueId) {
426 String csarUUID = payloadName;
427 String csarVersion = null;
428 Resource updatedResource = null;
429 if (payloadName == null) {
430 csarUUID = resource.getCsarUUID();
431 csarVersion = resource.getCsarVersion();
433 if (csarUUID != null && !csarUUID.isEmpty()) {
434 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
435 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
436 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
437 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
438 overrideImmutableMetadata(oldResource, resource);
440 validateResourceBeforeCreate(resource, user, false);
441 String oldCsarVersion = oldResource.getCsarVersion();
442 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
444 // (on boarding flow): If the update includes same csarUUID and
445 // same csarVersion as already in the VF - no need to import the
446 // csar (do only metadata changes if there are).
447 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
448 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
450 updatedResource = updateResourceFromCsar(oldResource, resource, user,
451 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
454 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
455 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
457 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
458 throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
460 return updatedResource;
463 private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
464 // (on boarding flow): If the update includes a csarUUID: verify this
465 // csarUUID is not in use by another VF, If it is - use same error as
467 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
468 // select another or update the existing VF." %1 - csarUUID, %2 - VF
470 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
471 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
472 if (resourceLinkedToCsarRes.isRight()) {
473 if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
474 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
475 resource.getSystemName());
476 throw new StorageException(resourceLinkedToCsarRes.right()
479 } else if (!resourceLinkedToCsarRes.left()
482 .equals(oldResource.getUniqueId())
483 && !resourceLinkedToCsarRes.left()
486 .equals(oldResource.getName())) {
487 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
488 resourceLinkedToCsarRes.left()
491 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
492 throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left()
498 private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID,
499 String resourceUniqueId, User user) {
500 // (on boarding flow): If the update includes csarUUID which is
501 // different from the csarUUID of the VF - fail with
502 // error: "Error: Resource %1 cannot be updated using since it is linked
503 // to a different VSP" %1 - VF name
504 String oldCsarUUID = oldResource.getCsarUUID();
505 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
507 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
508 resourceUniqueId, csarUUID, oldCsarUUID);
509 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
510 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
511 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
512 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID,
517 private Resource getResourceByUniqueId(String resourceUniqueId) {
518 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade
519 .getToscaFullElement(resourceUniqueId);
520 if (oldResourceRes.isRight()) {
521 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
522 oldResourceRes.right()
524 throw new StorageException(oldResourceRes.right()
527 return oldResourceRes.left()
531 private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
532 resource.setName(oldResource.getName());
533 resource.setIcon(oldResource.getIcon());
534 resource.setTags(oldResource.getTags());
535 resource.setCategories(oldResource.getCategories());
536 resource.setDerivedFrom(oldResource.getDerivedFrom());
539 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user,
540 AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload,
542 Resource updatedResource = null;
543 validateLifecycleState(oldResource, user);
544 String lockedResourceId = oldResource.getUniqueId();
545 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
546 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
547 lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
549 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
551 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
552 nodeTypesInfo, csarInfo, oldResource);
553 if (findNodeTypesArtifactsToHandleRes.isRight()) {
554 log.debug("failed to find node types for update with artifacts during import csar {}. ",
555 csarInfo.getCsarUUID());
556 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right()
559 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
563 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts,
564 csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo,
565 nodeTypesArtifactsToHandle, null, false);
567 } catch (ComponentException | StorageException e) {
568 rollback(inTransaction, newResource, createdArtifacts, null);
572 janusGraphDao.commit();
573 log.debug("unlock resource {}", lockedResourceId);
574 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
576 return updatedResource;
580 private void validateLifecycleState(Resource oldResource, User user) {
581 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState()
582 && !oldResource.getLastUpdaterUserId()
583 .equals(user.getUserId())) {
585 "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
586 oldResource.getLastUpdaterUserId(), user.getUserId());
587 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
591 private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
592 List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
593 Map<String, NodeTypeInfo> nodeTypesInfo,
594 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
595 String nodeName, boolean isNested) {
596 boolean inTransaction = true;
597 boolean shouldLock = false;
598 Resource preparedResource = null;
599 ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
601 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName,
602 nodeTypesInfo, csarInfo, nodeName);
603 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
604 if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
605 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
607 preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(),
608 inTransaction, shouldLock, isNested).left;
609 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
610 handleResourceGenericType(preparedResource);
611 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle,
612 createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
613 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
614 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
615 preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
616 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames);
617 } catch (ComponentException e) {
618 ResponseFormat responseFormat = e.getResponseFormat() == null
619 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
620 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
622 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
623 preparedResource == null ? oldResource : preparedResource, actionEnum);
625 } catch (StorageException e) {
626 ResponseFormat responseFormat = componentsUtils
627 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
628 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
630 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
631 preparedResource == null ? oldResource : preparedResource, actionEnum);
634 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
635 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
636 preparedResource.getSystemName());
637 if (validateUpdateVfGroupNamesRes.isRight()) {
639 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right()
642 // add groups to newResource
643 Map<String, GroupDefinition> groups;
645 if (!validateUpdateVfGroupNamesRes.left()
648 groups = validateUpdateVfGroupNamesRes.left()
651 groups = uploadComponentInstanceInfoMap.getGroups();
653 handleGroupsProperties(preparedResource, groups);
654 Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
656 preparedResource = updateGroupsOnResource(preparedResource, groups);
658 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
659 nodeTypesArtifactsToHandle);
661 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE,
662 createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts,
663 inTransaction, shouldLock);
664 if (updateArtifactsEither.isRight()) {
665 log.debug("failed to update artifacts {}", updateArtifactsEither.right()
667 throw new ByResponseFormatComponentException(updateArtifactsEither.right()
670 preparedResource = getResourceWithGroups(updateArtifactsEither.left()
674 updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
675 updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
677 preparedResource = getResourceWithGroups(preparedResource.getUniqueId());
679 updateVolumeGroup(preparedResource);
681 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
682 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
683 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
685 throw new ByResponseFormatComponentException(responseFormat);
687 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
689 return preparedResource;
692 protected void updateVolumeGroup(Resource preparedResource) {
693 List<GroupDefinition> groups = preparedResource.safeGetGroups();
694 for (GroupDefinition group : groups) {
695 Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
696 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
697 List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
698 if (!volumePropList.isEmpty()) {
699 PropertyDataDefinition volumeProp = volumePropList.get(0);
700 if (volumeProp != null) {
701 boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
703 if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
704 volumeProp.setValue(String.valueOf(isVolumeGroup));
705 volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
713 private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
714 if (CollectionUtils.isNotEmpty(oldResource.getGroups())
715 && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
716 Map<String, String> oldGroups = oldResource.getGroups()
718 .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
720 List<GroupDefinition> updatedGroups = preparedResource.getGroups()
722 .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
723 .equals(oldGroups.get(group.getInvariantName())))
726 if (CollectionUtils.isNotEmpty(updatedGroups)) {
727 if (isTopologyChanged) {
728 updatedGroups.stream().filter(group -> !group.isVspOriginated())
729 .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
731 updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
733 groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
738 private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource, boolean isTopologyChanged) {
739 if(CollectionUtils.isNotEmpty(oldResource.getComponentInstances())){
740 Map<String, String> oldInstances = oldResource.getComponentInstances()
742 .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
743 List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
745 .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
746 .equals(oldInstances.get(i.getInvariantName())))
748 if (CollectionUtils.isNotEmpty(updatedInstances)) {
749 if(isTopologyChanged) {
750 updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
751 .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
754 updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
759 componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
760 null, preparedResource.getUniqueId(), csarInfo.getModifier()
762 preparedResource.getComponentInstances(), false);
765 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
766 List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
767 Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
768 boolean inTransaction, boolean shouldLock) {
770 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
771 Resource resource = preparedResource;
773 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
774 .getNodeTypesArtifactsToHandle();
775 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
776 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
777 && !nodeTypesArtifactsToHandle.get(nodeName)
779 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
780 preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
781 csarInfo.getModifier(), inTransaction, true);
782 if (handleNodeTypeArtifactsRes.isRight()) {
783 return Either.right(handleNodeTypeArtifactsRes.right()
788 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
789 csarInfo, createdArtifacts,
790 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock,
792 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
793 if (createdCsarArtifactsEither.isRight()) {
794 return createdCsarArtifactsEither;
797 resource = createdCsarArtifactsEither.left()
800 return Either.left(resource);
803 private Resource handleResourceGenericType(Resource resource) {
804 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
805 if (resource.shouldGenerateInputs()) {
806 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
808 return genericResource;
811 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
812 final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
814 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
815 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
816 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
819 final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
820 .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
821 final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
822 nodeTypesInfo, oldResource.getName(), csarInfo);
823 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
824 oldResource.getName(), csarInfo.getCsarUUID());
825 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
826 nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
827 } catch (Exception e) {
828 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
829 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
830 log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
832 return nodeTypesArtifactsToHandleRes;
835 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
836 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
837 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
838 ImmutablePair<String, String> vfcToscaNames) {
840 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
841 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
842 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
844 if (!isEmpty(extractedVfcsArtifacts)) {
845 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
846 if (extractedVfcsArtifacts.containsKey(namespace)) {
847 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
849 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
850 } else if (curNodeType != null) {
851 // delete all artifacts if have not received artifacts from
853 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
854 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
855 // delete all informational artifacts
856 artifactsToDelete.addAll(curNodeType.getArtifacts()
859 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
861 // delete all deployment artifacts
862 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
864 if (!artifactsToDelete.isEmpty()) {
865 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
868 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
869 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
873 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
874 String previousVfcToscaName, StorageOperationStatus status) {
875 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
876 log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
878 ResponseFormat responseFormat = componentsUtils
879 .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
880 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
881 AuditingActionEnum.CREATE_RESOURCE);
882 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
883 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
884 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
886 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
891 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
892 List<ArtifactDefinition> extractedArtifacts) {
894 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
896 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
897 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
898 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
899 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
900 artifactsToDelete, collectExistingArtifacts(curNodeType));
901 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
902 } catch (Exception e) {
903 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
904 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
906 return nodeTypeArtifactsToHandle;
909 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
910 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
911 List<ArtifactDefinition> artifactsToDelete) {
912 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
913 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
914 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
915 if (!artifactsToUpload.isEmpty()) {
916 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
918 if (!artifactsToUpdate.isEmpty()) {
919 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
921 if (!artifactsToDelete.isEmpty()) {
922 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
925 return nodeTypeArtifactsToHandle;
928 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
929 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
930 List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
931 if (!existingArtifacts.isEmpty()) {
932 extractedArtifacts.stream()
933 .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
934 artifactsToDelete.addAll(existingArtifacts.values());
938 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
939 List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
940 ArtifactDefinition currNewArtifact) {
941 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
943 .filter(a -> a.getArtifactName()
944 .equals(currNewArtifact.getArtifactName()))
946 if (foundArtifact.isPresent()) {
947 if (foundArtifact.get()
949 .equals(currNewArtifact.getArtifactType())) {
950 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
951 existingArtifacts.remove(foundArtifact.get()
952 .getArtifactLabel());
953 artifactsToUpload.remove(currNewArtifact);
955 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
956 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
957 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
963 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
964 ArtifactDefinition foundArtifact) {
965 if (!foundArtifact.getArtifactChecksum()
966 .equals(currNewArtifact.getArtifactChecksum())) {
967 foundArtifact.setPayload(currNewArtifact.getPayloadData());
968 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
969 foundArtifact.setArtifactChecksum(
970 GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
971 artifactsToUpdate.add(foundArtifact);
975 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
976 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
977 if (curNodeType == null) {
978 return existingArtifacts;
980 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
981 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
983 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
984 existingArtifacts.putAll(curNodeType.getArtifacts()
987 .filter(e -> e.getValue()
988 .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
989 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
991 return existingArtifacts;
995 * Changes resource life cycle state to checked out
999 * @param inTransaction
1002 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
1003 Either<Resource, ResponseFormat> checkoutResourceRes;
1005 if (!resource.getComponentMetadataDefinition()
1006 .getMetadataDataDefinition()
1008 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
1010 "************* Going to change life cycle state of resource {} to not certified checked out. ",
1011 resource.getName());
1012 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
1013 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1014 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1015 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
1016 inTransaction, true);
1017 if (checkoutRes.isRight()) {
1018 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
1019 resource.getComponentType()
1021 resource.getUniqueId(), checkoutRes.right()
1024 checkoutResourceRes = Either.right(checkoutRes.right()
1027 checkoutResourceRes = Either.left((Resource) checkoutRes.left()
1031 checkoutResourceRes = Either.left(resource);
1033 } catch (Exception e) {
1034 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1035 checkoutResourceRes = Either.right(responseFormat);
1036 log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
1039 return checkoutResourceRes;
1043 * Handles Artifacts of NodeType
1045 * @param nodeTypeResource
1046 * @param nodeTypeArtifactsToHandle
1048 * @param inTransaction
1051 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
1052 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1053 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
1054 List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
1055 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1056 Either<Resource, ResponseFormat> changeStateResponse;
1058 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1059 if (changeStateResponse.isRight()) {
1060 return Either.right(changeStateResponse.right()
1063 nodeTypeResource = changeStateResponse.left()
1066 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1067 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1068 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1070 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1071 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1072 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1073 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
1074 nodeTypeResource.getName());
1075 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1076 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
1077 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
1078 ignoreLifecycleState, curOperation),
1079 false, inTransaction);
1080 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1081 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1083 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1086 if (handleNodeTypeArtifactsRes == null) {
1087 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1089 } catch (Exception e) {
1090 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1091 handleNodeTypeArtifactsRes = Either.right(responseFormat);
1092 log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1094 return handleNodeTypeArtifactsRes;
1097 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
1098 final String vfResourceName,
1099 final CsarInfo csarInfo) {
1100 final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
1102 final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
1103 if (!nodes.isEmpty()) {
1104 final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
1105 while (nodesNameEntry.hasNext()) {
1106 final Entry<String, Object> nodeType = nodesNameEntry.next();
1107 final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
1108 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
1109 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
1112 for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
1113 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
1114 vfResourceName, cvfc.getType()));
1116 return vfcToscaNames;
1119 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1120 Map<String, Object> nodes = new HashMap<>();
1121 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
1122 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
1124 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
1128 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
1129 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1130 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
1131 if (eitherNodeTypes.isLeft()) {
1132 nodes.putAll(eitherNodeTypes.left()
1137 public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
1139 log.trace("************* created successfully from YAML, resource TOSCA ");
1140 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
1141 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
1142 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
1143 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
1144 nodeTypesInfo, csarInfo, resource);
1145 if (findNodeTypesArtifactsToHandleRes.isRight()) {
1146 log.debug("failed to find node types for update with artifacts during import csar {}. ",
1147 csarInfo.getCsarUUID());
1148 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1149 StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
1150 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
1152 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
1153 csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
1156 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
1157 vfResource.getToscaResourceName());
1158 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
1162 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1163 log.trace("validating resource before create");
1164 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
1165 // validate user role
1166 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
1167 // VF / PNF "derivedFrom" should be null (or ignored)
1168 if (ModelConverter.isAtomicComponent(resource)) {
1169 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1171 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1175 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
1176 // nodeTypesArtifactsToCreate, true, false, null
1177 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1178 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1179 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1180 boolean shouldLock, boolean inTransaction, String nodeName) {
1182 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
1183 Resource createdResource;
1185 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
1186 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
1187 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1189 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
1190 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1191 StatusCode.STARTED,"");
1192 createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1193 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
1194 csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1195 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
1196 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1197 StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
1198 } catch (ComponentException e) {
1199 ResponseFormat responseFormat = e.getResponseFormat() == null
1200 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
1201 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1202 AuditingActionEnum.IMPORT_RESOURCE);
1204 } catch (StorageException e) {
1205 ResponseFormat responseFormat = componentsUtils
1206 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1207 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1208 AuditingActionEnum.IMPORT_RESOURCE);
1211 return createdResource;
1215 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
1216 Map<String, Object> mappedToscaTemplate, boolean needLock,
1217 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1218 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1219 CsarInfo csarInfo) {
1221 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1222 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1223 if (toscaVersion.isRight()) {
1224 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1226 Map<String, Object> mapToConvert = new HashMap<>();
1227 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
1229 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1230 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1231 nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1232 return csarInfo.getCreatedNodes();
1235 private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1236 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1238 .orValue(HashMap::new);
1241 private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1242 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1243 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1244 CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1245 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
1247 Resource vfcCreated = null;
1248 while (nodesNameValueIter.hasNext()) {
1249 Entry<String, Object> nodeType = nodesNameValueIter.next();
1250 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1251 || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1253 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1254 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1255 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1256 nodeTypesInfo, csarInfo, nodeType.getKey());
1257 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1258 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1259 && !csarInfo.getCreatedNodesToscaResourceNames()
1260 .containsKey(nodeType.getKey())) {
1261 log.trace("************* Going to create node {}", nodeType.getKey());
1262 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
1263 nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
1264 nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1265 log.debug("************* Finished to create node {}", nodeType.getKey());
1267 vfcCreated = resourceCreated.getLeft();
1268 csarInfo.getCreatedNodesToscaResourceNames()
1269 .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1271 if (vfcCreated != null) {
1272 csarInfo.getCreatedNodes()
1273 .put(nodeType.getKey(), vfcCreated);
1275 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1279 private Resource handleNestedVfc(Resource resource,
1280 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1281 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1284 String yamlName = nodesInfo.get(nodeName)
1285 .getTemplateFileName();
1286 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
1287 .getMappedToscaTemplate();
1289 log.debug("************* Going to create node types from yaml {}", yamlName);
1290 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
1291 createdArtifacts, nodesInfo, csarInfo);
1292 log.debug("************* Finished to create node types from yaml {}", yamlName);
1294 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1295 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1296 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
1297 nodeName, yamlName);
1302 private Resource handleComplexVfc(final Resource resource,
1303 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
1304 nodesArtifactsToHandle,
1305 final List<ArtifactDefinition>
1306 createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1307 final String nodeName, final String yamlName) {
1309 Resource oldComplexVfc = null;
1310 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1311 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1312 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1313 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1314 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1315 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1317 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1318 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1319 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1320 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1321 } else if (oldComplexVfcRes.isLeft()) {
1322 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1323 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1324 oldComplexVfcRes.left().value(),
1325 newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1326 if (eitherValidation.isLeft()) {
1327 oldComplexVfc = oldComplexVfcRes.left().value();
1330 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
1331 yamlName, oldComplexVfc, newComplexVfc);
1332 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1333 final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1334 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1335 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1336 final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
1337 lifecycleChangeInfo, true, false, true);
1338 csarInfo.getCreatedNodes().put(nodeName, result);
1339 csarInfo.removeNodeFromQueue();
1343 private Resource handleComplexVfc(
1344 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1345 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1346 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1348 Resource handleComplexVfcRes;
1349 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
1350 .getMappedToscaTemplate();
1351 String yamlContent = new String(csarInfo.getCsar()
1353 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
1355 .collect(toMap(Entry::getKey, e -> e.getValue()
1356 .getUnmarkedCopy()));
1357 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1358 if (oldComplexVfc == null) {
1359 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1360 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1362 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1363 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1364 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1366 return handleComplexVfcRes;
1369 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1370 Map<String, NodeTypeInfo> nodesInfo) {
1372 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1373 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1374 csarInfo.addNodeToQueue(nodeName);
1375 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
1379 private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
1381 final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
1382 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1383 final String resourceType = findTypes[0];
1384 return nameWithouNamespacePrefix.substring(resourceType.length());
1387 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
1388 final Entry<String, Object> nodeNameValue,
1390 final Map<String, Object> mapToConvert,
1391 final Resource resourceVf,
1392 final boolean needLock,
1393 final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1394 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1395 final boolean forceCertificationAllowed,
1396 final CsarInfo csarInfo,
1397 final boolean isNested) {
1399 final UploadResourceInfo resourceMetaData = fillResourceMetadata(
1400 yamlName, resourceVf, nodeNameValue.getKey(), user);
1402 final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1403 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1404 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1405 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1406 nodeNameValue.getKey(), isNested);
1409 private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
1410 final Map<String, Object> mapToConvert,
1411 final String nodeResourceType,
1412 final CsarInfo csarInfo) {
1413 // We need to create a Yaml from each node_types in order to create
1414 // resource from each node type using import normative flow.
1415 final DumperOptions options = new DumperOptions();
1416 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1417 final Yaml yaml = new Yaml(options);
1419 final Map<String, Object> node = new HashMap<>();
1420 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1421 .getLeft(), nodeNameValue.getValue());
1422 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1424 return yaml.dumpAsMap(mapToConvert);
1427 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1428 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1432 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
1433 UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1434 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1435 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1436 String nodeName, boolean isNested) {
1438 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1439 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1440 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1442 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1443 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1444 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1448 * Validates if a given node type name has a valid prefix.
1450 * @param nodeName node name from definition file
1451 * @param definedResourceNamespaceList is a list of all node type name prefix allowed
1452 * @return a valid node type name prefix if it`s found
1454 public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
1455 final List<String> definedResourceNamespaceList) {
1456 for (final String validNamespace : definedResourceNamespaceList) {
1457 if (nodeName.startsWith(validNamespace)) {
1458 return Optional.of(validNamespace);
1461 return Optional.empty();
1464 private List<String> getDefinedNodeTypeNamespaceList() {
1465 return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
1468 private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
1469 final String nodeName, final User user) {
1471 final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1473 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
1474 log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
1476 if (!nodeName.startsWith(nodeTypeNamePrefix)) {
1477 log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
1478 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1479 resourceMetaData.getName(), nodeName);
1482 final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
1483 final String namePrefix = nodeName.replace(actualName, "");
1484 String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
1485 log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
1486 resourceType, nodeName, actualName, nodeTypeNamePrefix);
1488 // if we import from csar, the node_type name can be
1489 // org.openecomp.resource.abstract.node_name - in this case we always
1491 if (resourceType.equals(Constants.ABSTRACT)) {
1492 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1495 if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
1496 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1500 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1501 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
1502 resourceType.toUpperCase(), ResourceTypeEnum.values());
1503 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1504 resourceMetaData.getName(), nodeName);
1508 resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
1510 // Setting type from name
1511 final String type = resourceType.toUpperCase();
1512 resourceMetaData.setResourceType(type);
1514 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1515 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1516 resourceMetaData.setContactId(user.getUserId());
1517 resourceMetaData.setVendorName(resourceVf.getVendorName());
1518 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1521 final List<String> tags = new ArrayList<>();
1522 tags.add(resourceMetaData.getName());
1523 resourceMetaData.setTags(tags);
1526 final CategoryDefinition category = new CategoryDefinition();
1527 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1528 final SubCategoryDefinition subCategory = new SubCategoryDefinition();
1529 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1530 category.addSubCategory(subCategory);
1531 final List<CategoryDefinition> categories = new ArrayList<>();
1532 categories.add(category);
1533 resourceMetaData.setCategories(categories);
1535 return resourceMetaData;
1538 private Resource buildComplexVfcMetadata(final Resource resourceVf,
1539 final CsarInfo csarInfo,
1540 final String nodeName,
1541 final Map<String, NodeTypeInfo> nodesInfo) {
1542 final Resource cvfc = new Resource();
1543 final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1544 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1545 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1546 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1547 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1548 cvfc.setAbstract(true);
1549 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1550 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1551 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1552 cvfc.setContactId(csarInfo.getModifier()
1554 cvfc.setCreatorUserId(csarInfo.getModifier()
1556 cvfc.setVendorName(resourceVf.getVendorName());
1557 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1558 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1559 cvfc.setToscaResourceName(buildNestedToscaResourceName(
1560 ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1561 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1563 final List<String> tags = new ArrayList<>();
1564 tags.add(cvfc.getName());
1567 final CategoryDefinition category = new CategoryDefinition();
1568 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1569 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1570 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1571 category.addSubCategory(subCategory);
1572 final List<CategoryDefinition> categories = new ArrayList<>();
1573 categories.add(category);
1574 cvfc.setCategories(categories);
1576 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1577 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1578 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1583 private String buildCvfcName(final String resourceVfName, final String nodeName) {
1585 String nameWithouNamespacePrefix =
1586 nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1587 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1588 String resourceType = findTypes[0];
1589 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1590 return addCvfcSuffixToResourceName(resourceName);
1593 private Resource createResourceAndRIsFromYaml(final String yamlName,
1595 final ParsedToscaYamlInfo parsedToscaYamlInfo,
1596 final AuditingActionEnum actionEnum,
1597 final boolean isNormative,
1598 final List<ArtifactDefinition> createdArtifacts,
1599 final String topologyTemplateYaml,
1600 final Map<String, NodeTypeInfo> nodeTypesInfo,
1601 final CsarInfo csarInfo,
1602 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1603 final boolean shouldLock,
1604 final boolean inTransaction,
1605 final String nodeName) {
1607 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1610 final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1612 if (lockResult.isRight()) {
1613 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1614 throw new ByResponseFormatComponentException(lockResult.right().value());
1616 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1619 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1620 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
1621 final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1622 resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
1623 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1624 log.trace("************* Going to add inputs from yaml {}", yamlName);
1625 if (resource.shouldGenerateInputs())
1626 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1628 final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1629 resource = createInputsOnResource(resource, inputs);
1630 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1631 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
1632 resource.getComponentMetadataForSupportLog(),
1633 StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
1634 if (resource.getResourceType() == ResourceTypeEnum.PNF) {
1635 log.trace("************* Adding generic properties to PNF");
1636 resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
1637 genericResource.getProperties());
1638 log.trace("************* Adding software information to PNF");
1639 softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
1640 log.trace("************* Removing non-mano software information file from PNF");
1641 if (csarInfo.getSoftwareInformationPath().isPresent() &&
1642 !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
1643 log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
1644 "catalog-be", "Could not remove the software information file.");
1648 final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1650 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1651 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName);
1652 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1653 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
1655 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1656 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
1657 resource.getComponentMetadataForSupportLog(),
1658 StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName);
1659 // validate update vf module group names
1660 final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1661 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1662 if (validateUpdateVfGroupNamesRes.isRight()) {
1663 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1664 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1666 // add groups to resource
1667 final Map<String, GroupDefinition> groups;
1668 log.trace("************* Going to add groups from yaml {}", yamlName);
1669 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
1670 StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
1671 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1672 groups = validateUpdateVfGroupNamesRes.left().value();
1674 groups = parsedToscaYamlInfo.getGroups();
1677 final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
1678 if (createGroupsOnResource.isRight()) {
1679 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1680 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1681 resource.getComponentMetadataForSupportLog(),
1682 StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
1683 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1685 resource = createGroupsOnResource.left().value();
1686 log.trace("************* Finished to add groups from yaml {}", yamlName);
1687 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1688 resource.getComponentMetadataForSupportLog(),
1689 StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
1690 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1691 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1692 resource.getComponentMetadataForSupportLog(),
1693 StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
1695 log.trace("************* Starting to add policies from yaml {}", yamlName);
1696 Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
1697 if (MapUtils.isNotEmpty(policies)) {
1698 resource = createPoliciesOnResource(resource, policies);
1700 log.trace("************* Finished to add policies from yaml {}", yamlName);
1702 final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
1703 new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
1705 final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
1706 ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
1707 nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1708 if (createArtifactsEither.isRight()) {
1709 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1710 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1711 resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
1712 createArtifactsEither.right().value());
1713 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1715 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1716 resource.getComponentMetadataForSupportLog(),
1717 StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
1718 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1719 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1720 ASDCKpiApi.countCreatedResourcesKPI();
1723 } catch (final ComponentException | StorageException e) {
1724 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1726 } catch (final ToscaOperationException e) {
1727 log.error("An error has occurred during resource and resource instance creation", e);
1728 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1729 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
1730 "catalog-be", e.getMessage());
1731 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1732 } catch (final BusinessLogicException e) {
1733 log.error("An error has occurred during resource and resource instance creation", e);
1734 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1735 throw new ByResponseFormatComponentException(e.getResponseFormat());
1737 if (!inTransaction) {
1738 janusGraphDao.commit();
1741 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1742 NodeTypeEnum.Resource);
1747 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1748 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1749 if (!inTransaction) {
1750 janusGraphDao.rollback();
1752 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1753 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1754 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
1755 resource.getName());
1759 private Resource getResourceWithGroups(String resourceId) {
1761 ComponentParametersView filter = new ComponentParametersView();
1762 filter.setIgnoreGroups(false);
1763 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
1765 if (updatedResource.isRight()) {
1766 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
1767 .value()), resourceId);
1769 return updatedResource.left()
1773 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1774 Map<String, GroupDefinition> groups) {
1775 if (groups != null && !groups.isEmpty()) {
1776 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1777 handleGroupsProperties(resource, groups);
1778 fillGroupsFinalFields(groupsAsList);
1779 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1780 groupsAsList, true);
1781 if (createGroups.isRight()) {
1782 return Either.right(createGroups.right()
1786 return Either.left(resource);
1789 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1790 List<InputDefinition> inputs = resource.getInputs();
1791 if (MapUtils.isNotEmpty(groups)) {
1794 .filter(g -> isNotEmpty(g.getProperties()))
1795 .flatMap(g -> g.getProperties()
1797 .forEach(p -> handleGetInputs(p, inputs));
1801 private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
1802 policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
1806 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1807 if (isNotEmpty(property.getGetInputValues())) {
1808 if (inputs == null || inputs.isEmpty()) {
1809 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1810 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1812 .map(GetInputValueDataDefinition::getInputName)
1816 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
1818 while (getInputValuesIter.hasNext()) {
1819 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1820 InputDefinition input = findInputByName(inputs, getInput);
1821 getInput.setInputId(input.getUniqueId());
1822 if (getInput.getGetInputIndex() != null) {
1823 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1824 input = findInputByName(inputs, getInputIndex);
1825 getInputIndex.setInputId(input.getUniqueId());
1826 getInputValuesIter.add(getInputIndex);
1832 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1833 Optional<InputDefinition> inputOpt = inputs.stream()
1834 .filter(p -> p.getName()
1835 .equals(getInput.getInputName()))
1837 if (!inputOpt.isPresent()) {
1838 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1839 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1841 return inputOpt.get();
1844 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1845 groupsAsList.forEach(groupDefinition -> {
1846 groupDefinition.setInvariantName(groupDefinition.getName());
1847 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1851 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1852 if (isEmpty(groups)) {
1855 return updateOrCreateGroups(resource, groups);
1858 private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1859 List<GroupDefinition> groupsFromResource = resource.getGroups();
1860 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1861 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1862 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1863 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1864 if (isNotEmpty(groupsFromResource)) {
1865 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1866 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1868 groupsToCreate.addAll(groupsAsList);
1870 if (isNotEmpty(groupsToCreate)) {
1871 fillGroupsFinalFields(groupsToCreate);
1872 if (isNotEmpty(groupsFromResource)) {
1873 groupBusinessLogic.addGroups(resource, groupsToCreate, true)
1875 .on(this::throwComponentException);
1877 groupBusinessLogic.createGroups(resource, groupsToCreate, true)
1879 .on(this::throwComponentException);
1882 if (isNotEmpty(groupsToDelete)) {
1883 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1885 .on(this::throwComponentException);
1887 if (isNotEmpty(groupsToUpdate)) {
1888 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1890 .on(this::throwComponentException);
1896 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1897 List<GroupDefinition> groupsToDelete) {
1898 for (GroupDefinition group : groupsFromResource) {
1899 Optional<GroupDefinition> op = groupsAsList.stream()
1900 .filter(p -> p.getInvariantName()
1901 .equalsIgnoreCase(group.getInvariantName()))
1903 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
1905 groupsToDelete.add(group);
1910 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1911 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1912 for (GroupDefinition group : groupsAsList) {
1913 Optional<GroupDefinition> op = groupsFromResource.stream()
1914 .filter(p -> p.getInvariantName()
1915 .equalsIgnoreCase(group.getInvariantName()))
1917 if (op.isPresent()) {
1918 GroupDefinition groupToUpdate = op.get();
1919 groupToUpdate.setMembers(group.getMembers());
1920 groupToUpdate.setCapabilities(group.getCapabilities());
1921 groupToUpdate.setProperties(group.getProperties());
1922 groupsToUpdate.add(groupToUpdate);
1924 groupsToCreate.add(group);
1929 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1930 List<InputDefinition> resourceProperties = resource.getInputs();
1931 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1933 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1935 if (createInputs.isRight()) {
1936 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
1937 StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
1939 throw new ByResponseFormatComponentException(createInputs.right()
1942 resource.setInputs(createInputs.left().value());
1947 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
1948 Resource component) {
1950 List<GroupDefinition> result = new ArrayList<>();
1951 List<ComponentInstance> componentInstances = component.getComponentInstances();
1953 if (groups != null) {
1954 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1955 if (validateCyclicGroupsDependencies.isRight()) {
1956 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
1958 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1959 String groupName = entry.getKey();
1960 GroupDefinition groupDefinition = entry.getValue();
1961 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1962 updatedGroupDefinition.setMembers(null);
1963 Map<String, String> members = groupDefinition.getMembers();
1964 if (members != null) {
1965 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
1968 result.add(updatedGroupDefinition);
1974 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
1975 Resource component, List<ComponentInstance> componentInstances, String groupName,
1976 Map<String, String> members) {
1977 Set<String> compInstancesNames = members.keySet();
1979 if (CollectionUtils.isEmpty(componentInstances)) {
1980 String membersAstString = compInstancesNames.stream()
1981 .collect(joining(","));
1983 "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1984 membersAstString, groupName, component.getNormalizedName());
1985 throw new ByActionStatusComponentException(
1986 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
1987 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
1989 // Find all component instances with the member names
1990 Map<String, String> memberNames = componentInstances.stream()
1991 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1992 memberNames.putAll(groups.keySet()
1994 .collect(toMap(g -> g, g -> "")));
1995 Map<String, String> relevantInstances = memberNames.entrySet()
1997 .filter(n -> compInstancesNames.contains(n.getKey()))
1998 .collect(toMap(Entry::getKey, Entry::getValue));
2000 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2002 List<String> foundMembers = new ArrayList<>();
2003 if (relevantInstances != null) {
2004 foundMembers = relevantInstances.keySet()
2008 compInstancesNames.removeAll(foundMembers);
2009 String membersAstString = compInstancesNames.stream()
2010 .collect(joining(","));
2011 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
2012 component.getNormalizedName());
2013 throw new ByActionStatusComponentException(
2014 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2015 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2017 updatedGroupDefinition.setMembers(relevantInstances);
2021 * This Method validates that there is no cyclic group dependencies. meaning
2022 * group A as member in group B which is member in group A
2027 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
2029 Either<Boolean, ResponseFormat> result = Either.left(true);
2031 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
2033 while (allGroupsItr.hasNext() && result.isLeft()) {
2034 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
2035 // Fetches a group member A
2036 String groupAName = groupAEntry.getKey();
2037 // Finds all group members in group A
2038 Set<String> allGroupAMembersNames = new HashSet<>();
2039 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
2040 // If A is a group member of itself found cyclic dependency
2041 if (allGroupAMembersNames.contains(groupAName)) {
2042 ResponseFormat responseFormat = componentsUtils
2043 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
2044 result = Either.right(responseFormat);
2047 } catch (Exception e) {
2048 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2049 result = Either.right(responseFormat);
2050 log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
2056 * This Method fills recursively the set groupMembers with all the members
2057 * of the given group which are also of type group.
2061 * @param allGroupMembers
2064 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
2065 Set<String> allGroupMembers) {
2067 // Found Cyclic dependency
2068 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
2071 GroupDefinition groupDefinition = allGroups.get(groupName);
2072 // All Members Of Current Group Resource Instances & Other Groups
2073 Set<String> currGroupMembers = groupDefinition.getMembers()
2075 // Filtered Members Of Current Group containing only members which
2077 List<String> currGroupFilteredMembers = currGroupMembers.stream()
2079 // Keep Only Elements of type group and not Resource Instances
2080 filter(allGroups::containsKey)
2082 // Add Filtered Elements to main Set
2083 peek(allGroupMembers::add)
2088 // Recursively call the method for all the filtered group members
2089 for (String innerGroupName : currGroupFilteredMembers) {
2090 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
2095 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
2096 Set<String> allGroupMembers) {
2098 boolean stop = false;
2099 // In Case Not Group Stop
2100 if (!allGroups.containsKey(groupName)) {
2103 // In Case Group Has no members stop
2105 GroupDefinition groupDefinition = allGroups.get(groupName);
2106 stop = isEmpty(groupDefinition.getMembers());
2109 // In Case all group members already contained stop
2111 final Set<String> allMembers = allGroups.get(groupName)
2114 Set<String> membersOfTypeGroup = allMembers.stream()
2116 // Filter In Only Group members
2117 filter(allGroups::containsKey)
2121 stop = allGroupMembers.containsAll(membersOfTypeGroup);
2126 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
2127 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
2128 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2130 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2133 log.debug("************* Going to create all nodes {}", yamlName);
2134 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
2135 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
2136 log.debug("************* Finished to create all nodes {}", yamlName);
2137 log.debug("************* Going to create all resource instances {}", yamlName);
2138 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
2139 resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
2140 csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
2141 log.debug("************* Finished to create all resource instances {}", yamlName);
2142 log.debug("************* Going to create all relations {}", yamlName);
2143 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
2144 log.debug("************* Finished to create all relations {}", yamlName);
2145 log.debug("************* Going to create positions {}", yamlName);
2146 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
2148 log.debug("************* Finished to set positions {}", yamlName);
2152 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
2153 List<ArtifactDefinition> artifactsToAdd) {
2154 List<String> vfcArtifactNames = vfcArtifacts.stream()
2155 .map(ArtifactDataDefinition::getArtifactName)
2157 artifactsToAdd.stream()
2159 if (!vfcArtifactNames.contains(a.getArtifactName())) {
2160 vfcArtifacts.add(a);
2162 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
2168 @SuppressWarnings("unchecked")
2169 private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
2170 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2171 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2172 CsarInfo csarInfo, String nodeName) {
2174 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2175 if (nodeTypeEntry.getValue()
2178 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
2179 csarInfo, nodeTypeEntry.getKey());
2180 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2183 Map<String, Object> mappedToscaTemplate = null;
2184 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
2185 mappedToscaTemplate = nodeTypesInfo.get(nodeName)
2186 .getMappedToscaTemplate();
2188 if (isEmpty(mappedToscaTemplate)) {
2189 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2191 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
2192 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2193 } catch (ComponentException e) {
2194 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
2195 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
2196 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2197 AuditingActionEnum.IMPORT_RESOURCE);
2199 } catch (StorageException e) {
2200 ResponseFormat responseFormat = componentsUtils
2201 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2202 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2203 AuditingActionEnum.IMPORT_RESOURCE);
2208 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
2209 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
2210 boolean inTransaction) {
2212 if (csarInfo.getCsar() != null) {
2213 String vendorLicenseModelId = null;
2214 String vfLicenseModelId = null;
2216 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
2217 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
2218 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
2219 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
2220 if (artifactEntry.getValue()
2222 .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
2223 vendorLicenseModelId = artifactEntry.getValue()
2226 if (artifactEntry.getValue()
2228 .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
2229 vfLicenseModelId = artifactEntry.getValue()
2236 // Specific Behavior for license artifacts
2237 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2238 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
2239 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
2240 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
2241 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
2242 shouldLock, inTransaction);
2243 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2244 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
2245 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
2246 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
2247 artifactOperation, null, true, shouldLock, inTransaction);
2249 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
2250 createdArtifacts, shouldLock, inTransaction, artifactOperation);
2251 if (eitherCreateResult.isRight()) {
2252 return Either.right(eitherCreateResult.right()
2256 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
2257 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
2259 if (artifacsMetaCsarStatus.isLeft()) {
2260 String artifactsFileName = artifacsMetaCsarStatus.left()
2263 String artifactsContents = artifacsMetaCsarStatus.left()
2266 Either<Resource, ResponseFormat> createArtifactsFromCsar;
2267 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
2268 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
2269 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
2271 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
2272 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
2276 if (createArtifactsFromCsar.isRight()) {
2277 log.debug("Couldn't create artifacts from artifacts.meta");
2278 return Either.right(createArtifactsFromCsar.right()
2282 return Either.left(createArtifactsFromCsar.left()
2286 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
2291 return Either.left(resource);
2294 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
2295 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
2296 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
2297 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
2298 boolean shouldLock, boolean inTransaction) {
2299 byte[] artifactFileBytes = null;
2301 if (csarInfo.getCsar()
2302 .containsKey(artifactPath)) {
2303 artifactFileBytes = csarInfo.getCsar()
2306 Either<Boolean, ResponseFormat> result = Either.left(true);
2307 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE
2308 || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
2309 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
2310 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic
2311 .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
2312 AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, shouldLock,
2314 if (handleDelete.isRight()) {
2315 result = Either.right(handleDelete.right()
2318 Either<ArtifactDefinition, Operation> value = handleDelete.left().value();
2319 if (value.isLeft()) {
2320 String updatedArtifactId = value.left().value().getUniqueId();
2321 if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2322 resource.getDeploymentArtifacts().remove(updatedArtifactId);
2324 resource.getArtifacts().remove(updatedArtifactId);
2331 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2332 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2333 ArtifactOperationEnum.CREATE);
2337 if (artifactFileBytes != null) {
2338 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
2339 artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
2340 artifactDescription, artifactFileBytes, null, isFromCsar);
2341 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
2342 .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
2344 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2345 if (eitherNonMetaArtifacts.isRight()) {
2346 BeEcompErrorManager.getInstance()
2347 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2348 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2349 ErrorSeverity.WARNING);
2350 return Either.right(eitherNonMetaArtifacts.right()
2353 ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
2354 createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
2360 private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
2361 if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
2362 resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
2364 resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
2368 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2369 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2372 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2373 List<ArtifactDefinition> createdArtifacts,
2374 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2375 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
2376 && eitherNonMetaArtifacts.isLeft()) {
2377 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
2379 if (eitherResult.isLeft()) {
2380 createdArtifacts.add(eitherResult.left()
2386 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2387 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2388 ArtifactOperationInfo artifactOperation) {
2390 Either<Resource, ResponseFormat> resStatus = null;
2391 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2394 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
2395 collectedWarningMessages);
2396 if (artifactPathAndNameList.isRight()) {
2397 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2398 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
2401 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2403 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
2404 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2405 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
2408 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2409 resource, artifactPathAndNameList.left()
2411 csarInfo.getModifier());
2413 if (findVfCsarArtifactsToHandleRes.isRight()) {
2414 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
2417 if (resStatus == null) {
2418 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
2422 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2423 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
2424 resStatus, vfCsarArtifactsToHandle);
2426 if (resStatus == null) {
2427 resStatus = Either.left(resource);
2429 } catch (Exception e) {
2430 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2431 log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2433 CsarUtils.handleWarningMessages(collectedWarningMessages);
2438 private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
2439 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2440 Either<Resource, ResponseFormat> resStatus,
2441 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2442 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2445 Optional<ResponseFormat> optionalCreateInDBError =
2446 // Stream of artifacts to be created
2447 currArtifactOperationPair.getValue()
2449 // create each artifact
2450 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2451 e.getArtifactName(), e.getArtifactType(),
2452 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2453 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2454 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2455 currArtifactOperationPair.getKey()),
2456 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2457 // filter in only error
2458 .filter(Either::isRight)
2460 // Convert the error from either to
2465 // Check if an error occurred
2467 // Error found on artifact Creation
2468 if (optionalCreateInDBError.isPresent()) {
2469 resStatus = Either.right(optionalCreateInDBError.get());
2476 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
2477 Map<String, Set<List<String>>> collectedWarningMessages) {
2478 List<NonMetaArtifactInfo> artifactPathAndNameList =
2479 // Stream of file paths contained in csar
2483 // Filter in only VF artifact path location
2484 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
2485 .matcher(e.getKey())
2487 // Validate and add warnings
2488 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2489 // Filter in Non Warnings
2490 .filter(Either::isLeft)
2491 // Convert from Either to NonMetaArtifactInfo
2496 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2497 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2498 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
2500 return Either.right(nonMetaArtifactInfo.getArtifactName());
2503 return Either.left(artifactPathAndNameList);
2506 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2507 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2509 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2510 // collect all Deployment and Informational artifacts of VF
2511 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
2513 existingArtifacts.addAll(resource.getDeploymentArtifacts()
2516 if (resource.getArtifacts() != null && !resource.getArtifacts()
2518 existingArtifacts.addAll(resource.getArtifacts()
2521 existingArtifacts = existingArtifacts.stream()
2522 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2523 // was created from HEAT.meta
2524 .filter(this::isNonMetaArtifact)
2527 List<String> artifactsToIgnore = new ArrayList<>();
2528 // collect IDs of Artifacts of VF which belongs to any group
2529 if (resource.getGroups() != null) {
2530 resource.getGroups()
2533 if (g.getArtifacts() != null && !g.getArtifacts()
2535 artifactsToIgnore.addAll(g.getArtifacts());
2539 existingArtifacts = existingArtifacts.stream()
2540 // filter artifacts which belongs to any group
2541 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
2543 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2546 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2547 boolean result = true;
2548 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2554 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2555 boolean result = true;
2556 if (artifact.getArtifactType() == null
2557 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2558 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2564 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
2565 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
2566 log.debug("#createResourceInstancesRelations - Going to create relations ");
2567 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations");
2568 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2569 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
2570 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
2572 "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
2573 resource.getUniqueId(), yamlName);
2574 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
2575 BeEcompErrorManager.getInstance()
2576 .logInternalDataError("createResourceInstancesRelations",
2577 "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2578 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2580 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2581 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2582 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2583 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2584 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2585 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2586 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2587 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2589 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2590 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2591 if (allDataTypes.isRight()) {
2592 JanusGraphOperationStatus status = allDataTypes.right()
2594 BeEcompErrorManager.getInstance()
2595 .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2596 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2597 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2598 StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
2599 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2600 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
2603 Resource finalResource = resource;
2604 uploadResInstancesMap.values()
2605 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2606 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
2607 instAttributes, existingNodeTypesByResourceNames, instInputs, i));
2608 resource.getComponentInstances()
2610 .filter(i -> !i.isCreatedFromCsar())
2611 .forEach(i->processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
2613 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2614 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2615 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2616 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2617 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2618 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2619 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2620 associateResourceInstances(yamlName, resource, relations);
2621 handleSubstitutionMappings(resource, uploadResInstancesMap);
2622 log.debug("************* in create relations, getResource start");
2623 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations");
2624 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2625 .getToscaFullElement(resource.getUniqueId());
2626 log.debug("************* in create relations, getResource end");
2627 if (eitherGetResource.isRight()) {
2628 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2629 StatusCode.ERROR,"ERROR while create relations");
2630 throw new ByResponseFormatComponentException(componentsUtils
2631 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
2632 .value()), resource));
2634 return eitherGetResource.left()
2638 private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
2639 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2640 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2641 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2642 Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, List<ComponentInstanceInput>> instInputs, Map<String, List<PropertyDefinition>> instAttributes) {
2643 Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
2644 if(foundInstance.isPresent()){
2645 if(MapUtils.isNotEmpty(foundInstance.get().getCapabilities())){
2646 instCapabilities.put(instance, foundInstance.get().getCapabilities());
2648 if(MapUtils.isNotEmpty(foundInstance.get().getRequirements())){
2649 instRequirements.put(instance, foundInstance.get().getRequirements());
2651 if(MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())){
2652 instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
2654 if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
2655 instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
2657 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
2658 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))){
2659 instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
2661 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
2662 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))){
2663 instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
2665 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
2666 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
2667 instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(PropertyDefinition::new).collect(toList()));
2672 private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
2673 if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
2674 return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
2676 return Optional.empty();
2679 private void associateResourceInstances(String yamlName, Resource resource,
2680 List<RequirementCapabilityRelDef> relations) {
2681 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2683 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2684 StorageOperationStatus status = relationsEither.right().value();
2685 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2687 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
2689 setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
2693 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2694 Map<String, List<PropertyDefinition>> instAttributes) {
2695 StorageOperationStatus addArtToInst;
2696 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2698 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2699 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2701 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2705 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2706 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2707 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2708 StorageOperationStatus addArtToInst;
2709 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2711 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2712 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2714 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2718 private void associateArtifactsToInstances(String yamlName, Resource resource,
2719 Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2720 StorageOperationStatus addArtToInst;
2722 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2723 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2724 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2725 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2729 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2730 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2731 StorageOperationStatus addArtToInst = toscaOperationFacade
2732 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2733 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2734 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2735 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2739 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2740 Map<String, List<ComponentInstanceInput>> instInputs) {
2741 if (MapUtils.isNotEmpty(instInputs)) {
2742 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2743 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2744 if (addInputToInst.isRight()) {
2746 StorageOperationStatus addInputToInstError = addInputToInst.right().value();
2747 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2748 addInputToInstError);
2749 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
2751 setComponentInstanceInputsOnComponent(resource, instInputs);
2755 private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2756 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
2757 if (componentInstancesInputs == null)
2758 componentInstancesInputs = new HashMap<>();
2759 componentInstancesInputs.putAll(instInputs);
2760 resource.setComponentInstancesInputs(componentInstancesInputs);
2763 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2764 Map<String, List<ComponentInstanceProperty>> instProperties) {
2765 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2766 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2767 if (addPropToInst.isRight()) {
2768 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2769 StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
2770 StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
2771 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2772 storageOperationStatus);
2773 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
2775 setComponentInstancePropertiesOnComponent(resource, instProperties);
2778 private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2779 Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
2780 if (componentInstanceProps == null )
2781 componentInstanceProps = new HashMap<>();
2782 componentInstanceProps.putAll(instProperties);
2783 resource.setComponentInstancesProperties(componentInstanceProps);
2786 private void handleSubstitutionMappings(Resource resource,
2787 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2788 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2789 Either<Resource, StorageOperationStatus> getResourceRes =
2790 updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
2791 if (getResourceRes.isRight()) {
2792 ResponseFormat responseFormat = componentsUtils
2793 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
2794 .value()), resource);
2795 throw new ByResponseFormatComponentException(responseFormat);
2800 private void addRelationsToRI(String yamlName, Resource resource,
2801 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2802 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2803 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2804 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2805 ComponentInstance currentCompInstance = null;
2806 for (ComponentInstance compInstance : componentInstancesList) {
2808 if (compInstance.getName()
2809 .equals(uploadComponentInstanceInfo.getName())) {
2810 currentCompInstance = compInstance;
2815 if (currentCompInstance == null) {
2816 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2817 resource.getUniqueId());
2818 BeEcompErrorManager.getInstance()
2819 .logInternalDataError(
2820 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2821 resource.getUniqueId(), ErrorSeverity.ERROR);
2822 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2825 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2826 if (addRelationToRiRes.getStatus() != 200) {
2827 throw new ByResponseFormatComponentException(addRelationToRiRes);
2833 private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
2834 if (resource.getComponentInstancesRelations() != null) {
2835 resource.getComponentInstancesRelations().addAll(relations);
2837 resource.setComponentInstancesRelations(relations);
2841 private void processComponentInstance(String yamlName, Resource resource,
2842 List<ComponentInstance> componentInstancesList,
2843 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2844 Map<String, List<ComponentInstanceProperty>> instProperties,
2845 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2846 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2847 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2848 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
2849 Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap,
2850 Map<String, List<ComponentInstanceInput>> instInputs,
2851 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2852 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2853 .filter(i -> i.getName()
2854 .equals(uploadComponentInstanceInfo.getName()))
2856 if (!currentCompInstanceOpt.isPresent()) {
2857 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2858 resource.getUniqueId());
2859 BeEcompErrorManager.getInstance()
2860 .logInternalDataError(
2861 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2862 resource.getUniqueId(), ErrorSeverity.ERROR);
2863 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2865 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2866 String resourceInstanceId = currentCompInstance.getUniqueId();
2867 Resource originResource = getOriginResource(originCompMap, currentCompInstance);
2868 if (isNotEmpty(originResource.getRequirements())) {
2869 instRequirements.put(currentCompInstance, originResource.getRequirements());
2871 if (isNotEmpty(originResource.getCapabilities())) {
2872 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2873 currentCompInstance, originResource);
2875 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
2877 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2879 if (originResource.getArtifacts() != null && !originResource.getArtifacts()
2881 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2883 if (originResource.getAttributes() != null && !originResource.getAttributes()
2885 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2887 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2888 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2889 originResource, currentCompInstance, instProperties, allDataTypes.left()
2891 if (addPropertiesValueToRiRes.getStatus() != 200) {
2892 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2895 addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
2901 private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2902 Resource originResource;
2903 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2904 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2905 .getToscaFullElement(currentCompInstance.getComponentUid());
2906 if (getOriginResourceRes.isRight()) {
2907 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2908 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2909 getOriginResourceRes);
2910 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
2911 .value()), currentCompInstance.getComponentUid());
2913 originResource = getOriginResourceRes.left()
2915 originCompMap.put(originResource.getUniqueId(), originResource);
2917 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2919 return originResource;
2922 private void processComponentInstanceCapabilities(
2923 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2924 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2925 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2926 Resource originResource) {
2927 Map<String, List<CapabilityDefinition>> originCapabilities;
2928 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2929 originCapabilities = new HashMap<>();
2930 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2931 originResource.getCapabilities()
2932 .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
2933 uploadComponentInstanceInfo.getCapabilities()
2935 .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
2936 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2938 originCapabilities = originResource.getCapabilities();
2940 instCapabilties.put(currentCompInstance, originCapabilities);
2943 private void updateCapabilityPropertiesValues(
2944 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2945 Map<String, List<CapabilityDefinition>> originCapabilities,
2946 Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2947 originCapabilities.values()
2949 .flatMap(Collection::stream)
2950 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2951 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
2956 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
2957 List<UploadCapInfo> capabilities) {
2958 for (UploadCapInfo capability : capabilities) {
2959 if (isNotEmpty(capability.getProperties())) {
2960 newPropertiesMap.put(capability.getName(), capability.getProperties()
2962 .collect(toMap(UploadInfo::getName, p -> p)));
2967 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
2968 List<CapabilityDefinition> capabilities) {
2969 List<CapabilityDefinition> list = capabilities.stream()
2970 .map(CapabilityDefinition::new)
2972 originCapabilities.put(type, list);
2975 private void updatePropertyValues(List<ComponentInstanceProperty> properties,
2976 Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
2977 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2980 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2981 Map<String, DataTypeDefinition> allDataTypes) {
2982 String value = null;
2983 List<GetInputValueDataDefinition> getInputs = null;
2984 boolean isValidate = true;
2985 if (null != propertyInfo && propertyInfo.getValue() != null) {
2986 getInputs = propertyInfo.getGet_input();
2987 isValidate = getInputs == null || getInputs.isEmpty();
2989 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2991 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2992 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2995 property.setValue(value);
2996 return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
2999 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
3000 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3001 Either<Resource, StorageOperationStatus> updateRes = null;
3002 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3003 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3004 StorageOperationStatus status = toscaOperationFacade
3005 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
3006 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3008 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
3009 resource.getUniqueId(), status);
3010 updateRes = Either.right(status);
3012 if (updateRes == null) {
3013 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
3014 updatedInstCapabilities, updatedInstRequirements);
3015 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
3016 updatedInstRequirements, resource);
3017 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3019 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
3020 resource.getUniqueId(), status);
3021 updateRes = Either.right(status);
3024 if (updateRes == null) {
3025 updateRes = Either.left(resource);
3030 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
3031 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3032 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
3033 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3035 componentInstances.stream()
3037 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
3038 .getCapabilitiesNamesToUpdate());
3039 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
3040 .getRequirementsNamesToUpdate());
3044 private void fillUpdatedInstRequirements(
3045 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
3046 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3047 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3048 Set<String> updatedReqNames = new HashSet<>();
3049 if (isNotEmpty(requirementsNamesToUpdate)) {
3050 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
3052 updatedRequirements.put(requirements.getKey(), requirements.getValue()
3054 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
3055 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3057 r.setParentName(r.getName());
3058 r.setName(requirementsNamesToUpdate.get(r.getName()));
3059 updatedReqNames.add(r.getName());
3062 .collect(toList()));
3065 if (isNotEmpty(updatedRequirements)) {
3066 updatedInstRequirements.put(instance, updatedRequirements);
3070 private void fillUpdatedInstCapabilities(
3071 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
3072 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3073 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3074 Set<String> updatedCapNames = new HashSet<>();
3075 if (isNotEmpty(capabilitiesNamesToUpdate)) {
3076 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
3078 updatedCapabilities.put(requirements.getKey(), requirements.getValue()
3080 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
3081 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3083 c.setParentName(c.getName());
3084 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
3085 updatedCapNames.add(c.getName());
3088 .collect(toList()));
3091 if (isNotEmpty(updatedCapabilities)) {
3092 updatedInstCapabilties.put(instance, updatedCapabilities);
3096 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
3097 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3098 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3100 ComponentInstance currentCompInstance = null;
3102 for (ComponentInstance compInstance : componentInstancesList) {
3104 if (compInstance.getName()
3105 .equals(nodesInfoValue.getName())) {
3106 currentCompInstance = compInstance;
3112 if (currentCompInstance == null) {
3113 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
3114 BeEcompErrorManager.getInstance()
3115 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
3116 resource.getUniqueId(), ErrorSeverity.ERROR);
3117 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3119 String resourceInstanceId = currentCompInstance.getUniqueId();
3121 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
3123 if (regMap != null) {
3124 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
3127 while (nodesRegValue.hasNext()) {
3128 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3130 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3131 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3132 log.debug("Going to create relation {}", uploadRegInfo.getName());
3133 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
3134 String regName = uploadRegInfo.getName();
3135 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3136 regCapRelDef.setFromNode(resourceInstanceId);
3137 log.debug("try to find available requirement {} ", regName);
3138 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3139 yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
3140 if (eitherReqStatus.isRight()) {
3141 log.debug("failed to find available requirement {} status is {}", regName,
3142 eitherReqStatus.right()
3144 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
3145 return eitherReqStatus.right()
3149 RequirementDefinition validReq = eitherReqStatus.left()
3151 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3152 .getRelationships();
3153 if (reqAndRelationshipPairList == null) {
3154 reqAndRelationshipPairList = new ArrayList<>();
3156 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3157 reqAndRelationshipPair.setRequirement(regName);
3158 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3159 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3160 RelationshipImpl relationship = new RelationshipImpl();
3161 relationship.setType(validReq.getCapability());
3162 reqAndRelationshipPair.setRelationships(relationship);
3164 ComponentInstance currentCapCompInstance = null;
3165 for (ComponentInstance compInstance : componentInstancesList) {
3166 if (compInstance.getName()
3167 .equals(uploadRegInfo.getNode())) {
3168 currentCapCompInstance = compInstance;
3173 if (currentCapCompInstance == null) {
3174 log.debug("The component instance with name {} not found on resource {} ",
3175 uploadRegInfo.getNode(), resource.getUniqueId());
3176 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
3177 BeEcompErrorManager.getInstance()
3178 .logInternalDataError(
3179 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
3180 resource.getUniqueId(), ErrorSeverity.ERROR);
3181 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3183 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3184 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3185 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3186 currentCapCompInstance, uploadRegInfo);
3187 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3188 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3189 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3190 if (aviableCapForRel == null) {
3191 log.debug("aviable capability was not found. req name is {} component instance is {}",
3192 validReq.getName(), currentCapCompInstance.getUniqueId());
3193 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());
3194 BeEcompErrorManager.getInstance()
3195 .logInternalDataError(
3196 "aviable capability was not found. req name is " + validReq.getName()
3197 + " component instance is " + currentCapCompInstance.getUniqueId(),
3198 resource.getUniqueId(), ErrorSeverity.ERROR);
3199 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3201 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3202 capReqRel.setRelation(reqAndRelationshipPair);
3203 reqAndRelationshipPairList.add(capReqRel);
3204 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3205 relations.add(regCapRelDef);
3208 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3209 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3211 return componentsUtils.getResponseFormat(ActionStatus.OK);
3214 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
3215 Resource originResource, ComponentInstance currentCompInstance,
3216 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3217 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3218 if (MapUtils.isNotEmpty(propMap)) {
3219 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
3220 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3222 if (CollectionUtils.isEmpty(originResource.getInputs())) {
3223 log.debug("failed to find properties ");
3224 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
3225 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
3227 originResource.getInputs()
3228 .forEach(p -> addInput(currPropertiesMap, p));
3229 for (List<UploadPropInfo> propertyList : propMap.values()) {
3230 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
3233 currPropertiesMap.values()
3234 .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
3235 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3239 private void processProperty(Resource resource, ComponentInstance currentCompInstance,
3240 Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
3241 List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
3242 UploadPropInfo propertyInfo = propertyList.get(0);
3243 String propName = propertyInfo.getName();
3244 if (!currPropertiesMap.containsKey(propName)) {
3245 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3246 StatusCode.ERROR,"ERROR failed to find property: {}",propName);
3247 log.debug("failed to find property {} ", propName);
3248 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
3250 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3251 ComponentInstanceInput property = null;
3253 String value = null;
3254 List<GetInputValueDataDefinition> getInputs = null;
3255 boolean isValidate = true;
3256 if (propertyInfo.getValue() != null) {
3257 getInputs = propertyInfo.getGet_input();
3258 isValidate = getInputs == null || getInputs.isEmpty();
3260 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3262 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3263 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3266 String innerType = null;
3267 property = new ComponentInstanceInput(curPropertyDef, value, null);
3269 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3271 property.setValue(validPropertyVAlue);
3273 if (isNotEmpty(getInputs)) {
3274 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3275 for (GetInputValueDataDefinition getInput : getInputs) {
3276 List<InputDefinition> inputs = resource.getInputs();
3277 if (CollectionUtils.isEmpty(inputs)) {
3278 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3279 StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
3280 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
3281 currentCompInstance.getUniqueId());
3282 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3285 Optional<InputDefinition> optional = inputs.stream()
3286 .filter(p -> p.getName()
3287 .equals(getInput.getInputName()))
3289 if (!optional.isPresent()) {
3290 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3291 StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
3292 log.debug("Failed to find input {} ", getInput.getInputName());
3293 // @@TODO error message
3294 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3296 InputDefinition input = optional.get();
3297 getInput.setInputId(input.getUniqueId());
3298 getInputValues.add(getInput);
3300 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3301 processGetInput(getInputValues, inputs, getInputIndex);
3303 property.setGetInputValues(getInputValues);
3305 instPropList.add(property);
3306 // delete overriden property
3307 currPropertiesMap.remove(property.getName());
3310 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
3311 GetInputValueDataDefinition getInputIndex) {
3312 Optional<InputDefinition> optional;
3313 if (getInputIndex != null) {
3314 optional = inputs.stream()
3315 .filter(p -> p.getName()
3316 .equals(getInputIndex.getInputName()))
3318 if (!optional.isPresent()) {
3319 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3320 // @@TODO error message
3321 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3323 InputDefinition inputIndex = optional.get();
3324 getInputIndex.setInputId(inputIndex.getUniqueId());
3325 getInputValues.add(getInputIndex);
3329 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
3330 String propName = prop.getName();
3331 if (!currPropertiesMap.containsKey(propName)) {
3332 currPropertiesMap.put(propName, prop);
3336 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3337 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
3338 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3340 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3341 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
3343 List<PropertyDefinition> listFromMap = originResource.getProperties();
3344 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3345 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3346 StatusCode.ERROR,"ERROR Failed to find properties");
3347 log.debug("failed to find properties");
3348 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3350 if (listFromMap == null || listFromMap.isEmpty()) {
3351 return componentsUtils.getResponseFormat(ActionStatus.OK);
3353 for (PropertyDefinition prop : listFromMap) {
3354 String propName = prop.getName();
3355 if (!currPropertiesMap.containsKey(propName)) {
3356 currPropertiesMap.put(propName, prop);
3359 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3360 if (propMap != null && propMap.size() > 0) {
3361 for (List<UploadPropInfo> propertyList : propMap.values()) {
3363 UploadPropInfo propertyInfo = propertyList.get(0);
3364 String propName = propertyInfo.getName();
3365 if (!currPropertiesMap.containsKey(propName)) {
3366 log.debug("failed to find property {} ", propName);
3367 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
3368 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3370 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3371 ComponentInstanceProperty property = null;
3373 String value = null;
3374 List<GetInputValueDataDefinition> getInputs = null;
3375 boolean isValidate = true;
3376 if (propertyInfo.getValue() != null) {
3377 getInputs = propertyInfo.getGet_input();
3378 isValidate = getInputs == null || getInputs.isEmpty();
3380 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3382 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3383 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3386 String innerType = null;
3387 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3389 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3390 property.setValue(validatePropValue);
3392 if (getInputs != null && !getInputs.isEmpty()) {
3393 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3394 for (GetInputValueDataDefinition getInput : getInputs) {
3395 List<InputDefinition> inputs = resource.getInputs();
3396 if (inputs == null || inputs.isEmpty()) {
3397 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
3398 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
3399 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
3401 .map(GetInputValueDataDefinition::getInputName)
3405 InputDefinition input = findInputByName(inputs, getInput);
3406 getInput.setInputId(input.getUniqueId());
3407 getInputValues.add(getInput);
3409 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3410 if (getInputIndex != null) {
3411 input = findInputByName(inputs, getInputIndex);
3412 getInputIndex.setInputId(input.getUniqueId());
3413 getInputValues.add(getInputIndex);
3418 property.setGetInputValues(getInputValues);
3420 instPropList.add(property);
3421 // delete overriden property
3422 currPropertiesMap.remove(property.getName());
3425 // add rest of properties
3426 if (!currPropertiesMap.isEmpty()) {
3427 for (PropertyDefinition value : currPropertiesMap.values()) {
3428 instPropList.add(new ComponentInstanceProperty(value));
3431 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3432 return componentsUtils.getResponseFormat(ActionStatus.OK);
3435 // US740820 Relate RIs according to capability name
3436 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3437 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3438 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
3439 .equals(uploadReqInfo.getCapabilityName())) {// get
3443 return findAvailableCapability(validReq, currentCapCompInstance);
3445 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3448 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3449 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3450 CapabilityDefinition cap = null;
3451 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3452 if (!capMap.containsKey(validReq.getCapability())) {
3455 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
3457 .filter(p -> p.getName()
3458 .equals(uploadReqInfo.getCapabilityName()))
3460 if (!capByName.isPresent()) {
3463 cap = capByName.get();
3465 if (isBoundedByOccurrences(cap)) {
3466 String leftOccurrences = cap.getLeftOccurrences();
3467 int left = Integer.parseInt(leftOccurrences);
3470 cap.setLeftOccurrences(String.valueOf(left));
3478 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
3479 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
3480 if (capMap.containsKey(validReq.getCapability())) {
3481 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3483 for (CapabilityDefinition cap : capList) {
3484 if (isBoundedByOccurrences(cap)) {
3485 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
3486 : cap.getMaxOccurrences();
3487 int left = Integer.parseInt(leftOccurrences);
3490 cap.setLeftOccurrences(String.valueOf(left));
3501 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
3502 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
3503 .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
3506 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3507 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3509 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3510 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3511 RequirementDefinition validRegDef = null;
3513 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3514 for (RequirementDefinition reqDef : entry.getValue()) {
3515 if (reqDef.getName()
3517 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3518 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3519 String leftOccurrences = reqDef.getLeftOccurrences();
3520 if (leftOccurrences == null) {
3521 leftOccurrences = reqDef.getMaxOccurrences();
3523 int left = Integer.parseInt(leftOccurrences);
3526 reqDef.setLeftOccurrences(String.valueOf(left));
3527 validRegDef = reqDef;
3533 validRegDef = reqDef;
3539 if (validRegDef != null) {
3544 for (RequirementDefinition reqDef : list) {
3545 if (reqDef.getName()
3547 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3548 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3549 String leftOccurrences = reqDef.getLeftOccurrences();
3550 if (leftOccurrences == null) {
3551 leftOccurrences = reqDef.getMaxOccurrences();
3553 int left = Integer.parseInt(leftOccurrences);
3556 reqDef.setLeftOccurrences(String.valueOf(left));
3557 validRegDef = reqDef;
3563 validRegDef = reqDef;
3569 if (validRegDef == null) {
3570 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3571 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3572 return Either.right(responseFormat);
3574 return Either.left(validRegDef);
3577 private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
3578 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
3580 Either<Resource, ResponseFormat> eitherResource;
3581 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3582 if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3583 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3584 throw new ByResponseFormatComponentException(responseFormat);
3586 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3587 nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
3589 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3590 uploadResInstancesMap.values()
3591 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
3592 existingNodeTypesByResourceNames, resourcesInstancesMap));
3593 if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
3594 Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
3596 .collect(toMap(Resource::getUniqueId, r -> r));
3597 oldResource.getComponentInstances()
3599 .filter(i -> !i.isCreatedFromCsar())
3600 .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
3601 getOriginResource(existingNodeTypesByUids, uiInst)));
3604 if (isNotEmpty(resourcesInstancesMap)) {
3606 toscaOperationFacade.associateComponentInstancesToComponent(resource,
3607 resourcesInstancesMap, false, oldResource != null);
3608 } catch (StorageException exp) {
3609 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
3610 log.debug("Failed to add component instances to container component {}", resource.getName());
3611 ResponseFormat responseFormat = componentsUtils
3612 .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
3613 eitherResource = Either.right(responseFormat);
3614 throw new ByResponseFormatComponentException(eitherResource.right().value());
3618 if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
3619 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3620 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3621 BeEcompErrorManager.getInstance()
3622 .logBeDaoSystemError(
3623 "Error when create resource instance from csar. ComponentInstances list empty");
3624 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3629 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3630 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
3631 Map<ComponentInstance, Resource> resourcesInstancesMap) {
3632 Either<Resource, ResponseFormat> eitherResource;
3633 log.debug("*************Going to create resource instances {}", yamlName);
3634 // updating type if the type is node type name - we need to take the
3636 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3637 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3638 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
3639 .getToscaResourceName());
3641 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3642 existingnodeTypeMap);
3644 ComponentInstance componentInstance = new ComponentInstance();
3645 componentInstance.setComponentUid(refResource.getUniqueId());
3646 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3647 if(directives != null && !directives.isEmpty()) {
3648 componentInstance.setDirectives(new ArrayList<>(directives));
3650 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3651 if (uploadNodeFilterInfo != null){
3652 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3653 componentInstance.getUniqueId()));
3655 ComponentTypeEnum containerComponentType = resource.getComponentType();
3656 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3657 if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3658 && isNotEmpty(refResource.getCapabilities())) {
3659 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3660 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3661 refResource.getUniqueId(), refResource.getCapabilities(),
3662 uploadComponentInstanceInfo.getCapabilities());
3663 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3666 if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
3667 Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
3668 Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
3669 Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
3670 .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
3671 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
3672 Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
3673 for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
3674 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
3675 to.setFile(entry.getValue().getFile());
3676 to.setType(entry.getValue().getType());
3677 toscaArtifacts.put(entry.getKey(), to);
3679 componentInstance.setToscaArtifacts(toscaArtifacts);
3682 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3683 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
3684 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3685 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3686 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3688 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3689 componentInstance.setName(uploadComponentInstanceInfo.getName());
3690 componentInstance.setIcon(origResource.getIcon());
3691 componentInstance.setCreatedFrom(CreatedFrom.CSAR);
3692 resourcesInstancesMap.put(componentInstance, origResource);
3695 private ComponentParametersView getComponentWithInstancesFilter() {
3696 ComponentParametersView parametersView = new ComponentParametersView();
3697 parametersView.disableAll();
3698 parametersView.setIgnoreComponentInstances(false);
3699 parametersView.setIgnoreInputs(false);
3700 // inputs are read when creating
3701 // property values on instances
3702 parametersView.setIgnoreUsers(false);
3703 return parametersView;
3706 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3707 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3708 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3709 if (originCapabilities.containsKey(currEntry.getKey())) {
3710 currEntry.getValue()
3712 .forEach(cap -> cap.setType(currEntry.getKey()));
3715 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3716 capabilities.getValue()
3719 if (uploadedCapabilities.containsKey(cap.getName())) {
3720 uploadedCapabilities.get(cap.getName())
3723 c.setName(cap.getName());
3724 c.setType(cap.getType());
3731 private Resource validateResourceInstanceBeforeCreate(String yamlName,
3732 UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
3735 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
3736 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3737 Resource refResource;
3738 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3739 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3741 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3742 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3743 if (findResourceEither.isRight()) {
3745 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type {}",
3746 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3747 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3749 refResource = findResourceEither.left().value();
3750 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3752 String componentState = refResource.getComponentMetadataDefinition()
3753 .getMetadataDataDefinition()
3755 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3757 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3758 refResource.getName(), componentState);
3759 throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
3760 refResource.getComponentType().getValue(),refResource.getName(), componentState);
3763 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3764 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3765 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3766 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3771 public Resource propagateStateToCertified(User user, Resource resource,
3772 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3773 boolean forceCertificationAllowed) {
3775 boolean failed = false;
3777 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3778 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3779 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3781 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3782 Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
3783 resource, user, false, inTransaction, needLock, false);
3786 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3787 } catch (ComponentException e) {
3789 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3793 BeEcompErrorManager.getInstance()
3794 .logBeSystemError("Change LifecycleState - Certify");
3795 if (!inTransaction) {
3796 janusGraphDao.rollback();
3798 } else if (!inTransaction) {
3799 janusGraphDao.commit();
3804 private Resource nodeFullCertification(String uniqueId, User user,
3805 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3806 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
3807 inTransaction, needLock);
3808 if(resourceResponse.isRight()){
3809 throw new ByResponseFormatComponentException(resourceResponse.right().value());
3811 return resourceResponse.left().value();
3814 private Resource nodeForceCertification(Resource resource, User user,
3815 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3816 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3820 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
3822 final boolean isNormative,
3823 final boolean isInTransaction,
3824 final boolean needLock,
3825 final CsarInfo csarInfo,
3826 final String nodeName,
3827 final boolean isNested) {
3829 ImmutablePair<Resource, ActionStatus> result = null;
3830 // check if resource already exists (search by tosca name = type)
3831 final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3832 final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3833 .getLatestByToscaResourceName(resource.getToscaResourceName());
3835 if (latestByToscaName.isLeft()) {
3836 Resource foundResource = latestByToscaName.left().value();
3837 // we don't allow updating names of top level types
3838 if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
3839 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3840 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3841 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3842 foundResource.getName(), resource.getToscaResourceName());
3843 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3844 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3845 throwComponentException(responseFormat);
3847 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3848 } else if (isNotFound(latestByToscaName)) {
3849 if (isNestedResource) {
3850 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
3851 isNested, nodeName);
3853 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3856 StorageOperationStatus status = latestByToscaName.right().value();
3857 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3858 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
3859 .convertFromStorageResponse(latestByToscaName.right().value()), resource);
3860 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3861 throwComponentException(responseFormat);
3866 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3867 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3870 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
3872 final boolean isNormative,
3873 final boolean isInTransaction,
3874 final boolean needLock,
3875 final CsarInfo csarInfo,
3876 final boolean isNested,
3877 final String nodeName) {
3878 final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3879 .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
3880 .name(), csarInfo.getVfResourceName(), nodeName).getRight());
3881 if (latestByToscaName.isLeft()) {
3882 final Resource nestedResource = (Resource) latestByToscaName.left().value();
3883 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3884 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
3885 resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3886 if (eitherValidation.isRight()) {
3887 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3889 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3891 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3895 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3896 return getResourceEither.isRight() && getResourceEither.right()
3897 .value() == StorageOperationStatus.NOT_FOUND;
3900 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
3901 boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3902 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3903 validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3904 final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
3906 Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
3907 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
3908 ASDCKpiApi.countImportResourcesKPI();
3909 return resourcePair;
3912 public boolean isResourceExist(String resourceName) {
3913 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3914 return latestByName.isLeft();
3917 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
3918 Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
3919 String lockedResourceId = oldResource.getUniqueId();
3920 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3921 oldResource.getVersion(), oldResource.getLifecycleState());
3922 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3924 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3925 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3926 mergeOldResourceMetadataWithNew(oldResource, newResource);
3928 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3929 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource,
3930 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3931 // contact info normalization
3932 newResource.setContactId(newResource.getContactId()
3934 PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
3935 // non-updatable fields
3936 newResource.setCreatorUserId(user.getUserId());
3937 newResource.setCreatorFullName(user.getFullName());
3938 newResource.setLastUpdaterUserId(user.getUserId());
3939 newResource.setLastUpdaterFullName(user.getFullName());
3940 newResource.setUniqueId(oldResource.getUniqueId());
3941 newResource.setVersion(oldResource.getVersion());
3942 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3943 newResource.setLifecycleState(oldResource.getLifecycleState());
3944 newResource.setUUID(oldResource.getUUID());
3945 newResource.setNormalizedName(oldResource.getNormalizedName());
3946 newResource.setSystemName(oldResource.getSystemName());
3947 if (oldResource.getCsarUUID() != null) {
3948 newResource.setCsarUUID(oldResource.getCsarUUID());
3950 if (oldResource.getImportedToscaChecksum() != null) {
3951 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3953 newResource.setAbstract(oldResource.isAbstract());
3955 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom()
3957 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3959 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType()
3961 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3963 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion()
3965 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3968 // created without tosca artifacts - add the placeholders
3969 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts()
3971 setToscaArtifactsPlaceHolders(newResource, user);
3974 if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3975 newResource.setInterfaces(oldResource.getInterfaces());
3978 if (CollectionUtils.isEmpty(newResource.getProperties())) {
3979 newResource.setProperties(oldResource.getProperties());
3982 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3983 .overrideComponent(newResource, oldResource);
3985 if (overrideResource.isRight()) {
3986 ResponseFormat responseFormat = componentsUtils
3987 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
3988 .value()), newResource);
3989 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3991 throwComponentException(responseFormat);
3993 updateCatalog(overrideResource.left()
3994 .value(), ChangeTypeEnum.LIFECYCLE);
3996 log.debug("Resource updated successfully!!!");
3997 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3998 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3999 ResourceVersionInfo.newBuilder()
4000 .state(oldResource.getLifecycleState()
4002 .version(oldResource.getVersion())
4005 resourcePair = new ImmutablePair<>(overrideResource.left()
4006 .value(), ActionStatus.OK);
4007 return resourcePair;
4009 if (resourcePair == null) {
4010 BeEcompErrorManager.getInstance()
4011 .logBeSystemError("Change LifecycleState - Certify");
4012 janusGraphDao.rollback();
4013 } else if (!inTransaction) {
4014 janusGraphDao.commit();
4017 log.debug("unlock resource {}", lockedResourceId);
4018 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4025 * Merge old resource with new. Keep old category and vendor name without
4028 * @param oldResource
4029 * @param newResource
4031 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4033 // keep old category and vendor name without change
4034 // merge the rest of the resource metadata
4035 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4036 newResource.setTags(oldResource.getTags());
4039 if (newResource.getDescription() == null) {
4040 newResource.setDescription(oldResource.getDescription());
4043 if (newResource.getVendorRelease() == null) {
4044 newResource.setVendorRelease(oldResource.getVendorRelease());
4047 if (newResource.getResourceVendorModelNumber() == null) {
4048 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4051 if (newResource.getContactId() == null) {
4052 newResource.setContactId(oldResource.getContactId());
4055 newResource.setCategories(oldResource.getCategories());
4056 if (newResource.getVendorName() == null) {
4057 newResource.setVendorName(oldResource.getVendorName());
4059 List<GroupDefinition>oldForUpdate = oldResource.getGroups();
4060 if(CollectionUtils.isNotEmpty(oldForUpdate)){
4061 List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
4063 groupForUpdate.stream().filter(group -> group.isVspOriginated())
4064 .forEach(group -> group.setName(group.getInvariantName()));
4066 newResource.setGroups(groupForUpdate);
4070 if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
4071 ResourceTypeEnum updatedResourceType = newResource.getResourceType();
4072 Component derivedFromResource = getParentComponent(newResource);
4073 if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
4074 Resource parentResource = (Resource) derivedFromResource;
4075 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
4076 parentResource.getResourceType() != updatedResourceType) {
4077 BeEcompErrorManager.getInstance()
4078 .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
4079 ErrorSeverity.ERROR);
4080 log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
4081 newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
4082 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
4089 private Component getParentComponent(Resource newResource) {
4090 String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
4091 Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
4092 if(latestByToscaResourceName.isRight()){
4093 BeEcompErrorManager.getInstance()
4094 .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
4095 log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
4096 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
4098 return latestByToscaResourceName.left().value();
4101 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
4102 boolean inTransaction, boolean needLock) {
4104 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
4106 return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4107 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
4109 .on(response -> failOnChangeState(response, user, oldResource, newResource));
4114 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
4115 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
4116 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4117 ResourceVersionInfo.newBuilder()
4118 .state(oldResource.getLifecycleState()
4120 .version(oldResource.getVersion())
4122 throw new ByResponseFormatComponentException(response);
4125 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
4126 boolean inTransaction, CsarInfo csarInfo) {
4128 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4129 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4130 validateLifecycleTypesCreate(user, resource, actionEnum);
4131 validateResourceType(user, resource, actionEnum);
4132 resource.setCreatorUserId(user.getUserId());
4133 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4134 resource.setContactId(resource.getContactId()
4136 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4137 String resourceSystemName;
4138 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4139 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4141 resourceSystemName = resource.getSystemName();
4143 resource.setToscaResourceName(CommonBeUtils
4144 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4147 // Generate invariant UUID - must be here and not in operation since it
4148 // should stay constant during clone
4150 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4151 resource.setInvariantUUID(invariantUUID);
4156 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4157 AuditingActionEnum actionEnum) {
4158 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4159 if (resource.getResourceType() == null) {
4160 log.debug("Invalid resource type for resource");
4161 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4162 eitherResult = Either.right(errorResponse);
4163 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4165 return eitherResult;
4168 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4169 AuditingActionEnum actionEnum) {
4170 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4171 if (resource.getInterfaces() != null && resource.getInterfaces()
4173 log.debug("validate interface lifecycle Types Exist");
4174 Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
4177 while (intItr.hasNext() && eitherResult.isLeft()) {
4178 InterfaceDefinition interfaceDefinition = intItr.next();
4179 String intType = interfaceDefinition.getUniqueId();
4180 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4181 .getInterface(intType);
4182 if (eitherCapTypeFound.isRight()) {
4183 if (eitherCapTypeFound.right()
4184 .value() == StorageOperationStatus.NOT_FOUND) {
4185 BeEcompErrorManager.getInstance()
4186 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
4187 "Interface", intType);
4188 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4189 intType, resource.getName());
4190 BeEcompErrorManager.getInstance()
4191 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4192 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
4197 ResponseFormat errorResponse = componentsUtils
4198 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4199 eitherResult = Either.right(errorResponse);
4200 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4205 return eitherResult;
4208 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4209 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4210 boolean inTransaction) {
4212 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4213 if (resource.getCapabilities() != null && resource.getCapabilities()
4215 log.debug("validate capability Types Exist - capabilities section");
4217 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
4220 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4221 eitherResult, typeEntry, inTransaction);
4222 if (eitherResult.isRight()) {
4223 return Either.right(eitherResult.right()
4229 if (resource.getRequirements() != null && resource.getRequirements()
4231 log.debug("validate capability Types Exist - requirements section");
4232 for (String type : resource.getRequirements()
4234 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4235 resource.getRequirements()
4237 actionEnum, eitherResult, type, inTransaction);
4238 if (eitherResult.isRight()) {
4239 return Either.right(eitherResult.right()
4245 return eitherResult;
4248 // @param typeObject- the object to which the validation is done
4249 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4250 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4251 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4252 boolean inTransaction) {
4253 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4254 .getCapabilityType(type, inTransaction);
4255 if (eitherCapTypeFound.isRight()) {
4256 if (eitherCapTypeFound.right()
4257 .value() == StorageOperationStatus.NOT_FOUND) {
4258 BeEcompErrorManager.getInstance()
4259 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4261 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4262 resource.getName());
4263 BeEcompErrorManager.getInstance()
4264 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4266 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
4269 ResponseFormat errorResponse = null;
4271 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4273 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4276 eitherResult = Either.right(errorResponse);
4277 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4279 return eitherResult;
4282 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4283 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4284 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4285 boolean inTransaction) {
4286 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4287 .getCapabilityType(typeEntry.getKey(), inTransaction);
4288 if (eitherCapTypeFound.isRight()) {
4289 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4290 BeEcompErrorManager.getInstance()
4291 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4292 typeEntry.getKey());
4293 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4294 typeEntry.getKey(), resource.getName());
4295 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4297 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4298 eitherCapTypeFound.right().value().name());
4299 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4300 typeEntry.getKey());
4301 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4302 return Either.right(errorResponse);
4304 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4305 if (capabilityTypeDefinition.getProperties() != null) {
4306 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4307 List<ComponentInstanceProperty> properties = capDef.getProperties();
4308 List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
4309 if (properties == null || properties.isEmpty()) {
4310 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4311 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4312 changedProperties.add(newProp);
4315 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4316 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4317 PropertyDefinition propFromDef = prop.getValue();
4318 boolean propFound = false;
4319 for (ComponentInstanceProperty cip : properties) {
4320 if (propFromDef.getName().equals(cip.getName())) {
4321 //merge property value and property description only, ignore other fields
4322 if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
4323 propFromDef.setDescription(cip.getDescription());
4325 propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
4326 if(cip.getValue() != null){
4327 propFromDef.setValue(cip.getValue());
4329 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4331 properties.remove(cip);
4336 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4339 if (!propsToAdd.isEmpty()) {
4340 changedProperties.addAll(propsToAdd);
4343 capDef.setProperties(changedProperties);
4346 return eitherResult;
4349 public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
4350 boolean isNormative, boolean inTransaction) {
4353 // lock new resource name in order to avoid creation resource with same
4355 Resource createdResource = null;
4356 if (!inTransaction) {
4357 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4359 if (lockResult.isRight()) {
4360 ResponseFormat responseFormat = lockResult.right().value();
4361 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4362 throw new ByResponseFormatComponentException(responseFormat);
4365 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4368 if (resource.deriveFromGeneric()) {
4369 handleResourceGenericType(resource);
4371 createdResource = createResourceTransaction(resource, user, isNormative);
4372 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4373 createdResource, actionEnum);
4374 ASDCKpiApi.countCreatedResourcesKPI();
4375 } catch (ComponentException e) {
4376 ResponseFormat responseFormat = e.getResponseFormat() == null
4377 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
4378 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4380 } catch (StorageException e) {
4381 ResponseFormat responseFormat = componentsUtils
4382 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
4383 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4386 if (!inTransaction) {
4387 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4388 NodeTypeEnum.Resource);
4391 return createdResource;
4394 private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
4395 // validate resource name uniqueness
4396 log.debug("validate resource name");
4397 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4398 resource.getName(), resource.getResourceType(), resource.getComponentType());
4399 if (eitherValidation.isRight()) {
4400 loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
4401 StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
4402 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4403 eitherValidation.right()
4405 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
4408 if (eitherValidation.left()
4410 log.debug("resource with name: {}, already exists", resource.getName());
4411 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
4412 StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
4413 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4414 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4417 log.debug("send resource {} to dao for create", resource.getName());
4419 createArtifactsPlaceHolderData(resource, user);
4422 log.debug("enrich resource with creator, version and state");
4423 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4424 resource.setVersion(INITIAL_VERSION);
4425 resource.setHighestVersion(true);
4426 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4427 resource.setAbstract(false);
4430 return toscaOperationFacade.createToscaComponent(resource)
4432 .on(r -> throwComponentExceptionByResource(r, resource));
4435 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
4436 ResponseFormat responseFormat = componentsUtils
4437 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
4438 throw new ByResponseFormatComponentException(responseFormat);
4441 private void createArtifactsPlaceHolderData(Resource resource, User user) {
4442 // create mandatory artifacts
4444 // TODO it must be removed after that artifact uniqueId creation will be
4445 // moved to ArtifactOperation
4447 setInformationalArtifactsPlaceHolder(resource, user);
4448 setDeploymentArtifactsPlaceHolder(resource, user);
4449 setToscaArtifactsPlaceHolders(resource, user);
4452 @SuppressWarnings("unchecked")
4454 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4455 Resource resource = (Resource) component;
4456 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4457 if (artifactMap == null) {
4458 artifactMap = new HashMap<>();
4460 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4462 .getDeploymentResourceArtifacts();
4463 if (deploymentResourceArtifacts != null) {
4464 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
4465 deploymentResourceArtifacts
4466 .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
4468 resource.setDeploymentArtifacts(artifactMap);
4471 private void processDeploymentResourceArtifacts(User user, Resource resource,
4472 Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
4473 boolean shouldCreateArtifact = true;
4474 Map<String, Object> artifactDetails = (Map<String, Object>) v;
4475 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4476 if (object != null) {
4477 List<String> artifactTypes = (List<String>) object;
4478 if (!artifactTypes.contains(resource.getResourceType()
4480 shouldCreateArtifact = false;
4484 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
4486 if (shouldCreateArtifact) {
4487 if (artifactsBusinessLogic != null) {
4488 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4489 resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
4490 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
4491 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4497 @SuppressWarnings("unchecked")
4498 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4499 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4500 if (artifactMap == null) {
4501 artifactMap = new HashMap<>();
4503 String resourceUniqueId = resource.getUniqueId();
4504 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
4506 .getExcludeResourceCategory();
4507 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
4509 .getExcludeResourceType();
4510 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4512 .getInformationalResourceArtifacts();
4513 List<CategoryDefinition> categories = resource.getCategories();
4514 boolean isCreateArtifact = true;
4515 if (exludeResourceCategory != null) {
4516 String category = categories.get(0)
4518 isCreateArtifact = exludeResourceCategory.stream()
4519 .noneMatch(e -> e.equalsIgnoreCase(category));
4521 if (isCreateArtifact && exludeResourceType != null) {
4522 String resourceType = resource.getResourceType()
4524 isCreateArtifact = exludeResourceType.stream()
4525 .noneMatch(e -> e.equalsIgnoreCase(resourceType));
4527 if (informationalResourceArtifacts != null && isCreateArtifact) {
4528 Set<String> keys = informationalResourceArtifacts.keySet();
4529 for (String informationalResourceArtifactName : keys) {
4530 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4531 .get(informationalResourceArtifactName);
4532 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4533 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4534 ArtifactGroupTypeEnum.INFORMATIONAL);
4535 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4539 resource.setArtifacts(artifactMap);
4549 public ResponseFormat deleteResource(String resourceId, User user) {
4550 ResponseFormat responseFormat;
4551 validateUserExists(user);
4553 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4554 if (resourceStatus.isRight()) {
4555 log.debug("failed to get resource {}", resourceId);
4556 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4560 Resource resource = resourceStatus.left()
4563 StorageOperationStatus result = StorageOperationStatus.OK;
4564 lockComponent(resourceId, resource, "Mark resource to delete");
4567 result = markComponentToDelete(resource);
4568 if (result == StorageOperationStatus.OK) {
4569 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4571 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4572 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4574 return responseFormat;
4577 if (result == null || result != StorageOperationStatus.OK) {
4578 janusGraphDao.rollback();
4580 janusGraphDao.commit();
4582 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
4587 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
4588 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4589 validateUserExists(user);
4590 Resource resource = null;
4591 StorageOperationStatus result = StorageOperationStatus.OK;
4592 boolean failed = false;
4595 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
4596 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
4597 if (resourceStatus.isRight()) {
4598 log.debug("failed to get resource {} version {}", resourceName, version);
4599 return componentsUtils
4600 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4601 .value()), resourceName);
4604 resource = resourceStatus.left()
4608 janusGraphDao.commit();
4610 if (resource != null) {
4611 lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
4613 result = markComponentToDelete(resource);
4614 if (result != StorageOperationStatus.OK) {
4615 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4616 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4617 return responseFormat;
4619 }catch (ComponentException e){
4623 if (failed || result == null || result != StorageOperationStatus.OK) {
4624 janusGraphDao.rollback();
4626 janusGraphDao.commit();
4628 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
4631 return responseFormat;
4634 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
4637 validateUserExists(user);
4640 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
4641 if (storageStatus.isRight()) {
4642 log.debug("failed to get resource by id {}", resourceId);
4643 return Either.right(componentsUtils
4644 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
4645 .value()), resourceId));
4647 if (!(storageStatus.left()
4648 .value() instanceof Resource)) {
4649 return Either.right(componentsUtils.getResponseFormatByResource(
4650 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4652 return Either.left(storageStatus.left()
4657 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4660 validateUserExists(userId);
4662 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4663 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4664 if (getResource.isRight()) {
4665 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4666 return Either.right(componentsUtils
4667 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
4668 .value()), resourceName));
4670 return Either.left(getResource.left()
4675 * updateResourceMetadata
4678 * - modifier data (userId)
4679 * @param inTransaction
4681 * @param resourceIdToUpdate
4682 * - the resource identifier
4683 * @param newResource
4684 * @return Either<Resource , responseFormat>
4686 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
4687 User user, boolean inTransaction) {
4689 validateUserExists(user.getUserId());
4691 log.debug("Get resource with id {}", resourceIdToUpdate);
4692 boolean needToUnlock = false;
4695 if (currentResource == null) {
4696 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4697 .getToscaElement(resourceIdToUpdate);
4698 if (storageStatus.isRight()) {
4699 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4700 componentsUtils.convertFromStorageResponse(storageStatus.right()
4705 currentResource = storageStatus.left()
4708 // verify that resource is checked-out and the user is the last
4710 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4711 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4715 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4716 NodeTypeEnum.Resource);
4717 if (lockResult != StorageOperationStatus.OK) {
4718 BeEcompErrorManager.getInstance()
4719 .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
4720 resourceIdToUpdate);
4721 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4722 ResponseFormat responseFormat = componentsUtils
4723 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4724 throw new ByResponseFormatComponentException(responseFormat);
4727 needToUnlock = true;
4729 // critical section starts here
4730 // convert json to object
4732 // Update and updated resource must have a non-empty "derivedFrom"
4734 // This code is not called from import resources, because of root
4735 // VF "derivedFrom" should be null (or ignored)
4736 if (ModelConverter.isAtomicComponent(currentResource)) {
4737 validateDerivedFromNotEmpty(null, newResource, null);
4738 validateDerivedFromNotEmpty(null, currentResource, null);
4740 newResource.setDerivedFrom(null);
4743 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4744 user, currentResource, false, true);
4745 if (dataModelResponse.isRight()) {
4746 log.debug("failed to update resource metadata!!!");
4747 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4750 log.debug("Resource metadata updated successfully!!!");
4751 return dataModelResponse.left()
4754 } catch (ComponentException | StorageException e) {
4755 rollback(inTransaction, newResource, null, null);
4758 if (!inTransaction) {
4759 janusGraphDao.commit();
4762 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4767 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4768 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4769 updateVfModuleGroupsNames(currentResource, newResource);
4770 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4771 // Setting last updater and uniqueId
4772 newResource.setContactId(newResource.getContactId()
4774 newResource.setLastUpdaterUserId(user.getUserId());
4775 newResource.setUniqueId(resourceIdToUpdate);
4776 // Cannot set highest version through UI
4777 newResource.setHighestVersion(currentResource.isHighestVersion());
4778 newResource.setCreationDate(currentResource.getCreationDate());
4780 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4781 newResource, user.getUserId(), inTransaction);
4783 if (processUpdateOfDerivedFrom.isRight()) {
4784 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4785 return Either.right(processUpdateOfDerivedFrom.right()
4789 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4790 if (isNotEmpty(newResource.getGroups())) {
4791 for (GroupDefinition group : newResource.getGroups()) {
4792 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
4793 groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
4794 .getMetadataDataDefinition()
4795 .getUniqueId(), user, newResource.getComponentType(), group, true, false);
4799 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4800 .updateToscaElement(newResource);
4802 if (dataModelResponse.isRight()) {
4803 ResponseFormat responseFormat = componentsUtils
4804 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
4805 .value()), newResource);
4806 return Either.right(responseFormat);
4807 } else if (dataModelResponse.left()
4809 log.debug("No response from updateResource");
4810 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4812 return Either.left(dataModelResponse.left()
4816 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4817 if (currentResource.getGroups() != null && !currentResource.getName()
4818 .equals(newResource.getName())) {
4819 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4821 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4823 newResource.setGroups(updatedGroups);
4827 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4828 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4829 if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
4830 .equals(DEFAULT_GROUP_VF_MODULE)) {
4831 String prefix = updatedGroup.getName()
4832 .substring(0, replacePattern.length());
4833 String newGroupName = updatedGroup.getName()
4834 .replaceFirst(prefix, with);
4835 updatedGroup.setName(newGroupName);
4837 return updatedGroup;
4841 * validateResourceFieldsBeforeCreate
4844 * - modifier data (userId)
4846 private void validateResourceFieldsBeforeCreate(User user, Resource resource,
4847 AuditingActionEnum actionEnum, boolean inTransaction) {
4848 componentValidator.validate(user, resource, actionEnum);
4849 // validate category
4850 log.debug("validate category");
4851 validateCategory(user, resource, actionEnum, inTransaction);
4852 // validate vendor name & release & model number
4853 log.debug("validate vendor name");
4854 validateVendorName(user, resource, actionEnum);
4855 log.debug("validate vendor release");
4856 validateVendorReleaseName(user, resource, actionEnum);
4857 log.debug("validate resource vendor model number");
4858 validateResourceVendorModelNumber(user, resource, actionEnum);
4860 log.debug("validate cost");
4861 validateCost(resource);
4862 // validate licenseType
4863 log.debug("validate licenseType");
4864 validateLicenseType(user, resource, actionEnum);
4865 // validate template (derived from)
4866 log.debug("validate derived from");
4867 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4868 resource.setDerivedFrom(null);
4870 validateDerivedFromExist(user, resource, actionEnum);
4871 // warn about non-updatable fields
4872 checkComponentFieldsForOverrideAttempt(resource);
4873 String currentCreatorFullName = resource.getCreatorFullName();
4874 if (currentCreatorFullName != null) {
4875 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4878 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4879 if (currentLastUpdaterFullName != null) {
4880 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4883 Long currentLastUpdateDate = resource.getLastUpdateDate();
4884 if (currentLastUpdateDate != null) {
4885 log.debug("Resource last update date is automatically set and cannot be updated");
4888 Boolean currentAbstract = resource.isAbstract();
4889 if (currentAbstract != null) {
4890 log.debug("Resource abstract is automatically set and cannot be updated");
4895 * validateResourceFieldsBeforeUpdate
4897 * @param currentResource
4898 * - Resource object to validate
4901 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4902 boolean inTransaction, boolean isNested) {
4903 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4904 warnNonEditableFields(currentResource, updateInfoResource);
4907 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4908 String currentResourceVersion = currentResource.getVersion();
4909 String updatedResourceVersion = updateInfoResource.getVersion();
4911 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4912 log.debug("Resource version is automatically set and cannot be updated");
4915 String currentCreatorUserId = currentResource.getCreatorUserId();
4916 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4918 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4919 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4922 String currentCreatorFullName = currentResource.getCreatorFullName();
4923 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4925 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4926 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4929 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4930 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4932 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4933 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4936 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4937 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4939 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4940 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4942 Long currentCreationDate = currentResource.getCreationDate();
4943 Long updatedCreationDate = updateInfoResource.getCreationDate();
4945 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4946 log.debug("Resource Creation date is automatically set and cannot be updated");
4949 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4950 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4952 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4953 log.debug("Resource last update date is automatically set and cannot be updated");
4956 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4957 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4959 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4960 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4963 Boolean currentAbstract = currentResource.isAbstract();
4964 Boolean updatedAbstract = updateInfoResource.isAbstract();
4966 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4967 log.debug("Resource abstract is automatically set and cannot be updated");
4970 Boolean currentHighestVersion = currentResource.isHighestVersion();
4971 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4973 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4974 log.debug("Resource highest version is automatically set and cannot be updated");
4977 String currentUuid = currentResource.getUUID();
4978 String updatedUuid = updateInfoResource.getUUID();
4980 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4981 log.debug("Resource UUID is automatically set and cannot be updated");
4984 log.debug("Resource Type cannot be updated");
4985 String currentInvariantUuid = currentResource.getInvariantUUID();
4986 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4988 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4989 log.debug("Resource invariant UUID is automatically set and cannot be updated");
4990 updateInfoResource.setInvariantUUID(currentInvariantUuid);
4994 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
4996 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4997 log.debug("validate resource name before update");
4998 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4999 log.debug("validate description before update");
5000 componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
5001 log.debug("validate icon before update");
5002 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5003 log.debug("validate tags before update");
5004 componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
5005 log.debug("validate vendor name before update");
5006 validateVendorName(null, updateInfoResource, null);
5007 log.debug("validate resource vendor model number before update");
5008 validateResourceVendorModelNumber(currentResource, updateInfoResource);
5009 log.debug("validate vendor release before update");
5010 validateVendorReleaseName(null, updateInfoResource, null);
5011 log.debug("validate contact info before update");
5012 componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
5013 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
5014 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5015 log.debug("validate category before update");
5016 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5019 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5020 String resourceNameUpdated = updateInfoResource.getName();
5021 String resourceNameCurrent = currentResource.getName();
5022 if (resourceNameCurrent.equals(resourceNameUpdated)) {
5025 // In case of CVFC type we should support the case of old VF with CVFC
5026 // instances that were created without the "Cvfc" suffix
5027 return currentResource.getResourceType() == ResourceTypeEnum.CVFC
5028 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5031 private String addCvfcSuffixToResourceName(String resourceName) {
5032 return resourceName + "Cvfc";
5035 private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
5037 String resourceNameUpdated = updateInfoResource.getName();
5038 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5039 if (isNested || !hasBeenCertified) {
5040 componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
5041 validateResourceNameUniqueness(updateInfoResource);
5042 currentResource.setName(resourceNameUpdated);
5043 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5044 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5047 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5048 resourceNameUpdated);
5049 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5054 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5055 String iconUpdated = updateInfoResource.getIcon();
5056 String iconCurrent = currentResource.getIcon();
5057 if (!iconCurrent.equals(iconUpdated)) {
5058 if (!hasBeenCertified) {
5059 componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
5061 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5062 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5067 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
5068 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5069 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5070 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5071 validateResourceVendorModelNumber(null, updateInfoResource, null);
5075 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5076 boolean hasBeenCertified, boolean inTransaction) {
5077 validateCategory(null, updateInfoResource, null, inTransaction);
5078 if (hasBeenCertified) {
5079 CategoryDefinition currentCategory = currentResource.getCategories()
5081 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
5083 CategoryDefinition updateCategory = updateInfoResource.getCategories()
5085 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
5087 if (!currentCategory.getName()
5088 .equals(updateCategory.getName())
5089 || !currentSubCategory.getName()
5090 .equals(updtaeSubCategory.getName())) {
5091 log.info("Category {} cannot be updated once the resource has been certified once.",
5092 currentResource.getCategories());
5093 ResponseFormat errorResponse = componentsUtils
5094 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5095 return Either.right(errorResponse);
5098 return Either.left(true);
5101 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5102 Resource updateInfoResource, boolean hasBeenCertified) {
5104 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5105 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5106 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5107 || updatedDerivedFrom.isEmpty()) {
5108 log.trace("Update normative types");
5109 return Either.left(true);
5112 String derivedFromCurrent = currentDerivedFrom.get(0);
5113 String derivedFromUpdated = updatedDerivedFrom.get(0);
5115 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5116 if (!hasBeenCertified) {
5117 validateDerivedFromExist(null, updateInfoResource, null);
5119 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5120 currentResource, updateInfoResource, null);
5122 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5124 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5125 return validateDerivedFromExtending;
5129 // For derived from, we must know whether it was actually changed,
5130 // otherwise we must do no action.
5131 // Due to changes it inflicts on data model (remove artifacts,
5132 // properties...), it's not like a flat field which can be
5133 // overwritten if not changed.
5134 // So we must indicate that derived from is not changed
5135 updateInfoResource.setDerivedFrom(null);
5137 return Either.left(true);
5140 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5141 Resource updateInfoResource, boolean hasBeenCertified) {
5143 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5144 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5145 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5146 || updatedDerivedFrom.isEmpty()) {
5147 log.trace("Update normative types");
5148 return Either.left(true);
5151 String derivedFromCurrent = currentDerivedFrom.get(0);
5152 String derivedFromUpdated = updatedDerivedFrom.get(0);
5154 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5155 if (!hasBeenCertified) {
5156 validateDerivedFromExist(null, updateInfoResource, null);
5158 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5159 currentResource, updateInfoResource, null);
5161 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5163 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5164 return validateDerivedFromExtending;
5168 return Either.left(true);
5171 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5172 if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
5176 String templateName = resource.getDerivedFrom()
5178 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5179 .validateToscaResourceNameExists(templateName);
5180 if (dataModelResponse.isRight()) {
5181 StorageOperationStatus storageStatus = dataModelResponse.right()
5183 BeEcompErrorManager.getInstance()
5184 .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5185 log.debug("request to data model failed with error: {}", storageStatus);
5186 ResponseFormat responseFormat = componentsUtils
5187 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5188 log.trace("audit before sending response");
5189 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5190 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
5191 } else if (!dataModelResponse.left()
5193 log.info("resource template with name: {}, does not exists", templateName);
5194 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5195 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5196 throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5200 // Tal G for extending inheritance US815447
5201 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5202 Resource updateInfoResource, AuditingActionEnum actionEnum) {
5203 String currentTemplateName = currentResource.getDerivedFrom()
5205 String updatedTemplateName = updateInfoResource.getDerivedFrom()
5208 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5209 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5210 if (dataModelResponse.isRight()) {
5211 StorageOperationStatus storageStatus = dataModelResponse.right()
5213 BeEcompErrorManager.getInstance()
5214 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5215 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5216 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5217 log.trace("audit before sending response");
5218 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5219 return Either.right(responseFormat);
5222 if (!dataModelResponse.left()
5224 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5225 currentTemplateName);
5226 ResponseFormat responseFormat = componentsUtils
5227 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5228 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5230 return Either.right(responseFormat);
5233 return Either.left(true);
5236 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5237 log.debug("validate resource derivedFrom field");
5238 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
5240 || (resource.getDerivedFrom()
5242 || (resource.getDerivedFrom()
5246 log.info("derived from (template) field is missing for the resource");
5247 ResponseFormat responseFormat = componentsUtils
5248 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5249 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5251 throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5255 private void validateResourceNameUniqueness(Resource resource) {
5257 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5258 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5259 resource.getComponentType());
5260 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
5262 log.debug("resource with name: {}, already exists", resource.getName());
5263 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
5264 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5265 } else if (resourceOperationResponse.isRight()) {
5266 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5267 throw new StorageException(resourceOperationResponse.right()
5272 private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5274 List<CategoryDefinition> categories = resource.getCategories();
5275 if (CollectionUtils.isEmpty(categories)) {
5276 log.debug(CATEGORY_IS_EMPTY);
5277 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5278 ComponentTypeEnum.RESOURCE.getValue());
5279 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5280 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5281 ComponentTypeEnum.RESOURCE.getValue());
5283 if (categories.size() > 1) {
5284 log.debug("Must be only one category for resource");
5285 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
5286 ComponentTypeEnum.RESOURCE.getValue());
5288 CategoryDefinition category = categories.get(0);
5289 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5290 if (CollectionUtils.isEmpty(subcategories)) {
5291 log.debug("Missinig subcategory for resource");
5292 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5294 if (subcategories.size() > 1) {
5295 log.debug("Must be only one sub category for resource");
5296 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5299 SubCategoryDefinition subcategory = subcategories.get(0);
5301 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5302 log.debug(CATEGORY_IS_EMPTY);
5303 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5304 ComponentTypeEnum.RESOURCE.getValue());
5305 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5306 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5307 ComponentTypeEnum.RESOURCE.getValue());
5309 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5310 log.debug(CATEGORY_IS_EMPTY);
5311 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5312 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5313 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5314 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
5315 ComponentTypeEnum.RESOURCE.getValue());
5318 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
5321 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
5322 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5323 ResponseFormat responseFormat;
5324 if (category != null && subcategory != null) {
5325 log.debug("validating resource category {} against valid categories list", category);
5326 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5327 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5328 if (categories.isRight()) {
5329 log.debug("failed to retrieve resource categories from JanusGraph");
5330 responseFormat = componentsUtils.getResponseFormat(categories.right()
5332 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5333 throw new ByActionStatusComponentException(categories.right()
5336 List<CategoryDefinition> categoryList = categories.left()
5338 Optional<CategoryDefinition> foundCategory = categoryList.stream()
5339 .filter(cat -> cat.getName()
5340 .equals(category.getName()))
5342 if (!foundCategory.isPresent()) {
5343 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5344 category, categoryList);
5345 failOnInvalidCategory(user, resource, actionEnum);
5347 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
5350 .filter(subcat -> subcat.getName()
5351 .equals(subcategory.getName()))
5353 if (!foundSubcategory.isPresent()) {
5355 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5356 subcategory, foundCategory.get()
5357 .getSubcategories());
5358 failOnInvalidCategory(user, resource, actionEnum);
5363 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
5364 ResponseFormat responseFormat;
5365 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5366 ComponentTypeEnum.RESOURCE.getValue());
5367 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5368 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5371 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
5372 String vendorRelease = resource.getVendorRelease();
5373 log.debug("validate vendor relese name");
5374 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5375 log.info("vendor relese name is missing.");
5376 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5377 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5378 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
5381 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
5384 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
5385 AuditingActionEnum actionEnum) {
5386 if (vendorRelease != null) {
5387 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
5388 log.info("vendor release exceds limit.");
5389 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5390 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5391 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5392 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
5393 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5396 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
5397 log.info("vendor release is not valid.");
5398 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
5399 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5400 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
5405 private void validateVendorName(User user, Resource resource,
5406 AuditingActionEnum actionEnum) {
5407 String vendorName = resource.getVendorName();
5408 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
5409 log.info("vendor name is missing.");
5410 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
5411 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5412 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
5414 validateVendorName(vendorName, user, resource, actionEnum);
5417 private void validateVendorName(String vendorName, User user, Resource resource,
5418 AuditingActionEnum actionEnum) {
5419 if (vendorName != null) {
5420 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
5421 log.info("vendor name exceds limit.");
5422 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5423 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5424 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5425 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5426 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5429 if (!ValidationUtils.validateVendorName(vendorName)) {
5430 log.info("vendor name is not valid.");
5431 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
5432 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5433 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME, vendorName);
5438 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
5439 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
5440 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
5441 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
5442 log.info("resource vendor model number exceeds limit.");
5443 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5444 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5445 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5446 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5447 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5448 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5450 // resource vendor model number is currently validated as vendor
5452 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
5453 log.info("resource vendor model number is not valid.");
5454 ResponseFormat errorResponse = componentsUtils
5455 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5456 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5457 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5463 private void validateCost(Resource resource) {
5464 String cost = resource.getCost();
5466 if (!ValidationUtils.validateCost(cost)) {
5467 log.debug("resource cost is invalid.");
5468 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5473 private void validateLicenseType(User user, Resource resource,
5474 AuditingActionEnum actionEnum) {
5475 log.debug("validate licenseType");
5476 String licenseType = resource.getLicenseType();
5477 if (licenseType != null) {
5478 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
5480 if (!licenseTypes.contains(licenseType)) {
5481 log.debug("License type {} isn't configured", licenseType);
5482 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5483 if (actionEnum != null) {
5484 // In update case, no audit is required
5485 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5487 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5492 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
5493 Resource updatedResource, String userId, boolean inTransaction) {
5494 Either<Operation, ResponseFormat> deleteArtifactByInterface;
5495 if (updatedResource.getDerivedFrom() != null) {
5496 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
5497 log.debug("1. Removing interface artifacts from graph");
5498 // Remove all interface artifacts of resource
5499 String resourceId = updatedResource.getUniqueId();
5500 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
5502 if (interfaces != null) {
5503 Collection<InterfaceDefinition> values = interfaces.values();
5504 for (InterfaceDefinition interfaceDefinition : values) {
5505 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
5507 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
5508 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
5509 if (operations != null) {
5510 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
5511 Operation operation = operationEntry.getValue();
5512 ArtifactDefinition implementation = operation.getImplementationArtifact();
5513 if (implementation != null) {
5514 String uniqueId = implementation.getUniqueId();
5515 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
5516 uniqueId, operationEntry.getKey(), interfaceType);
5517 // only thing that transacts and locks here
5518 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
5519 userId, uniqueId, true);
5520 if (deleteArtifactByInterface.isRight()) {
5521 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
5522 if (!inTransaction) {
5523 janusGraphDao.rollback();
5525 return Either.right(deleteArtifactByInterface.right()
5529 log.trace("No implementation found for operation {} - nothing to delete",
5530 operationEntry.getKey());
5534 log.trace("No operations found for interface type {}", interfaceType);
5538 log.debug("2. Removing properties");
5539 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
5540 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
5542 if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
5543 log.debug("Failed to remove all properties of resource");
5544 if (!inTransaction) {
5545 janusGraphDao.rollback();
5547 return Either.right(componentsUtils
5548 .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
5553 log.debug("Derived from wasn't changed during update");
5556 if (inTransaction) {
5557 return Either.left(true);
5559 janusGraphDao.commit();
5560 return Either.left(true);
5564 /**** Auditing *******************/
5566 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
5567 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
5568 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
5570 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
5572 return webApplicationContext.getBean(class1);
5575 public ICapabilityTypeOperation getCapabilityTypeOperation() {
5576 return capabilityTypeOperation;
5580 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
5581 this.capabilityTypeOperation = capabilityTypeOperation;
5584 public Boolean validatePropertiesDefaultValues(Resource resource) {
5585 log.debug("validate resource properties default values");
5586 List<PropertyDefinition> properties = resource.getProperties();
5587 if (properties != null) {
5588 iterateOverProperties(properties);
5593 public void iterateOverProperties(List<PropertyDefinition> properties) {
5595 String innerType = null;
5596 for (PropertyDefinition property : properties) {
5597 if (!propertyOperation.isPropertyTypeValid(property)) {
5598 log.info("Invalid type for property {}", property);
5599 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
5600 property.getType(), property.getName());
5603 Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
5604 type = property.getType();
5606 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5607 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
5608 if (responseFormat != null) {
5612 validateDefaultPropertyValue(property, allDataTypes, type, innerType);
5616 private void validateDefaultPropertyValue(PropertyDefinition property,
5617 Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
5618 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
5619 log.info("Invalid default value for property {}", property);
5620 ResponseFormat responseFormat;
5621 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5622 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
5623 property.getName(), type, innerType, property.getDefaultValue());
5625 throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
5626 property.getName(), type, property.getDefaultValue());
5630 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
5631 Map<String, DataTypeDefinition> allDataTypes) {
5632 ResponseFormat responseFormat = null;
5633 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
5635 innerType = propertyInnerTypeValid.getLeft();
5636 if (!propertyInnerTypeValid.getRight()
5638 log.info("Invalid inner type for property {}", property);
5639 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
5640 property.getName());
5642 return responseFormat;
5646 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
5647 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
5651 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
5652 return componentInstanceBusinessLogic;
5655 private String getComponentTypeForResponse(Component component) {
5656 String componentTypeForResponse = "SERVICE";
5657 if (component instanceof Resource) {
5658 componentTypeForResponse = ((Resource) component).getResourceType()
5661 return componentTypeForResponse;
5664 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
5667 validateUserExists(user);
5669 // get resource from csar uuid
5670 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
5671 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
5672 if (either.isRight()) {
5673 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
5675 return Either.right(resp);
5678 return Either.left(either.left()
5683 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5684 String componentId, String userId) {
5688 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
5689 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5690 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5692 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5693 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
5694 defaultCapabilities, validCapabilitiesMap));
5695 return validCapabilitiesMap;
5698 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
5699 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5700 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
5701 String capabilityType = capabilities.get(0)
5703 if (defaultCapabilities.containsKey(capabilityType)) {
5704 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5705 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5706 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5707 validCapabilityList.add(defaultCapability);
5708 validCapabilitiesMap.put(key, validCapabilityList);
5710 throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
5714 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
5715 CapabilityDefinition defaultCapability) {
5716 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
5717 .getProperties())) {
5718 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5719 defaultCapability.getName(), resourceId);
5720 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
5721 defaultCapability.getName());
5722 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
5723 } else if (isNotEmpty(capabilities.get(0)
5724 .getProperties())) {
5725 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5729 private CapabilityDefinition getCapability(String resourceId,
5730 Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5731 CapabilityDefinition defaultCapability;
5732 if (isNotEmpty(defaultCapabilities.get(capabilityType)
5734 .getProperties())) {
5735 defaultCapability = defaultCapabilities.get(capabilityType)
5738 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5739 .getToscaFullElement(resourceId);
5740 if (getFullComponentRes.isRight()) {
5741 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
5743 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
5745 defaultCapability = getFullComponentRes.left()
5748 .get(capabilityType)
5751 return defaultCapability;
5754 private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
5755 UploadCapInfo uploadedCapability) {
5756 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5757 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
5759 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5760 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5761 for (UploadPropInfo property : uploadedProperties) {
5762 String propertyName = property.getName()
5764 String propertyType = property.getType();
5765 ComponentInstanceProperty validProperty;
5766 if (defaultProperties.containsKey(propertyName)
5767 && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5768 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
5770 validProperty = new ComponentInstanceProperty();
5771 validProperty.setName(propertyName);
5772 if (property.getValue() != null) {
5773 validProperty.setValue(property.getValue()
5776 validProperty.setDescription(property.getDescription());
5777 validProperty.setPassword(property.isPassword());
5778 validProperties.add(validProperty);
5780 defaultCapability.setProperties(validProperties);
5783 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
5784 String propertyType) {
5785 return propertyType != null && !defaultProperties.get(propertyName)
5787 .equals(propertyType);
5790 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5791 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5792 Resource resource, User user) {
5794 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5795 ArtifactOperationEnum.class);
5796 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5797 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5798 .left(nodeTypeArtifactsToHandle);
5800 // add all found Csar artifacts to list to upload
5801 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5802 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5803 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5804 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5805 ArtifactDefinition foundArtifact;
5807 if (!existingArtifactsToHandle.isEmpty()) {
5808 foundArtifact = existingArtifactsToHandle.stream()
5809 .filter(a -> a.getArtifactName()
5810 .equals(currNewArtifact.getArtifactName()))
5813 if (foundArtifact != null) {
5814 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
5815 if (!foundArtifact.getArtifactChecksum()
5816 .equals(currNewArtifact.getArtifactChecksum())) {
5817 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5818 // if current artifact already exists, but has
5819 // different content, add him to the list to
5821 artifactsToUpdate.add(currNewArtifact);
5823 // remove found artifact from the list of existing
5824 // artifacts to handle, because it was already
5826 existingArtifactsToHandle.remove(foundArtifact);
5827 // and remove found artifact from the list to
5828 // upload, because it should either be updated or be
5830 artifactsToUpload.remove(currNewArtifact);
5832 log.debug("Can't upload two artifact with the same name {}.",
5833 currNewArtifact.getArtifactName());
5834 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
5835 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5836 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
5837 foundArtifact.getArtifactType());
5838 AuditingActionEnum auditingAction = artifactsBusinessLogic
5839 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5840 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5841 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5842 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5843 resource.getComponentType(), null);
5844 responseWrapper.setInnerElement(responseFormat);
5850 if (responseWrapper.isEmpty()) {
5851 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5852 if (currArtifact.getIsFromCsar()) {
5853 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5854 currArtifact.getArtifactType(),
5855 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5856 currArtifact.getIsFromCsar()));
5858 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5859 currArtifact.getArtifactType(),
5860 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5861 currArtifact.getIsFromCsar()));
5866 if (responseWrapper.isEmpty()) {
5867 if (!artifactsToUpload.isEmpty()) {
5868 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5870 if (!artifactsToUpdate.isEmpty()) {
5871 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5873 if (!artifactsToDelete.isEmpty()) {
5874 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5877 if (!responseWrapper.isEmpty()) {
5878 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5880 } catch (Exception e) {
5881 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5882 responseWrapper.setInnerElement(responseFormat);
5883 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5885 return nodeTypeArtifactsToHandleRes;
5888 ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
5889 final String vfResourceName,
5890 final String nodeTypeFullName) {
5892 String actualVfName;
5893 if (ResourceTypeEnum.CVFC.name()
5894 .equals(nodeResourceType)) {
5895 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5896 actualType = ResourceTypeEnum.VFC.name();
5898 actualVfName = vfResourceName;
5899 actualType = nodeResourceType;
5901 String nameWithouNamespacePrefix;
5903 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
5904 log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
5905 + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName,
5906 nodeTypeFullName, actualType, vfResourceName);
5907 final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
5909 if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
5910 nameWithouNamespacePrefix = nodeTypeFullName;
5912 nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
5914 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5916 if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
5917 actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
5919 actualName = "." + nameWithouNamespacePrefix;
5922 if (actualName.startsWith(Constants.ABSTRACT)) {
5923 toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
5924 .append(ValidationUtils.convertToSystemName(actualVfName));
5926 toscaResourceName.append(actualType.toLowerCase()).append('.')
5927 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5929 final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5930 final String[] actualNames = actualName.split("\\.");
5931 if (actualNames.length < 3) {
5932 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5933 previousToscaResourceName.append(actualName).toString());
5935 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5936 previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
5937 .toLowerCase()).toString());
5938 } catch (final Exception e) {
5939 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5940 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5945 * Extracts a Node Type Name prefix from the given Node Type Name.
5947 * @param fullName Node Type Name
5948 * @return Node Type Name Prefix
5950 private String getNodeTypeNamePrefix(final String fullName) {
5951 String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
5952 final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
5953 log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
5954 final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
5955 if (validNameSpace.isPresent()) {
5956 tempPrefix = validNameSpace.get();
5958 log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
5963 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
5964 List<String> dataParamsToReturn) {
5966 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5967 Either<Resource, StorageOperationStatus> resourceResultEither =
5968 toscaOperationFacade.getToscaElement(resourceId,
5971 if (resourceResultEither.isRight()) {
5972 if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
5973 log.debug("Failed to found resource with id {} ", resourceId);
5975 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5978 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5979 return Either.right(componentsUtils
5980 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
5984 Resource resource = resourceResultEither.left().value();
5985 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
5986 ListUtils.emptyIfNull(resource.getInputs())
5987 .forEach(input -> input.setConstraints(setInputConstraint(input)));
5990 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5991 dataParamsToReturn);
5992 return Either.left(dataTransfer);
5996 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5997 Resource resource = (Resource) clonedComponent;
5998 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5999 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
6000 .shouldUpgradeToLatestDerived(resource);
6001 if (shouldUpgradeToLatestDerived.isRight()) {
6002 return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
6005 return Either.left(shouldUpgradeToLatestDerived.left()
6008 return super.shouldUpgradeToLatestDerived(clonedComponent);