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.artifact.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 != null ? oldResource.getCsarVersion() : null;
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 final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
678 preparedResource = getResourceWithGroups(preparedResourceId);
680 updateVolumeGroup(preparedResource);
682 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
683 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
684 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
686 throw new ByResponseFormatComponentException(responseFormat);
688 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
690 return preparedResource;
693 protected void updateVolumeGroup(Resource preparedResource) {
694 List<GroupDefinition> groups = preparedResource.safeGetGroups();
695 for (GroupDefinition group : groups) {
696 Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
697 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
698 List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
699 if (!volumePropList.isEmpty()) {
700 PropertyDataDefinition volumeProp = volumePropList.get(0);
701 if (volumeProp != null) {
702 boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
704 if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
705 volumeProp.setValue(String.valueOf(isVolumeGroup));
706 volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
714 private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
715 if (oldResource == null || preparedResource == null) {
716 log.debug("Failed to update groups name : oldResource or preparedResource is null");
717 } else if (CollectionUtils.isNotEmpty(oldResource.getGroups())
718 && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
719 Map<String, String> oldGroups = oldResource.getGroups()
721 .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
723 List<GroupDefinition> updatedGroups = preparedResource.getGroups()
725 .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
726 .equals(oldGroups.get(group.getInvariantName())))
729 if (CollectionUtils.isNotEmpty(updatedGroups)) {
730 if (isTopologyChanged) {
731 updatedGroups.stream().filter(group -> !group.isVspOriginated())
732 .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
734 updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
736 groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
741 private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource,
742 boolean isTopologyChanged) {
743 if (oldResource == null || preparedResource == null) {
744 log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
745 } else if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
746 Map<String, String> oldInstances = oldResource.getComponentInstances()
748 .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
749 List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
751 .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
752 .equals(oldInstances.get(i.getInvariantName())))
754 if (CollectionUtils.isNotEmpty(updatedInstances)) {
755 if (isTopologyChanged) {
756 updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
757 .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
759 updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
764 componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
765 null, preparedResource.getUniqueId(), csarInfo.getModifier()
767 preparedResource.getComponentInstances(), false);
770 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
771 List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
772 Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
773 boolean inTransaction, boolean shouldLock) {
775 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
776 Resource resource = preparedResource;
778 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
779 .getNodeTypesArtifactsToHandle();
780 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
781 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
782 && !nodeTypesArtifactsToHandle.get(nodeName)
784 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
785 preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
786 csarInfo.getModifier(), inTransaction, true);
787 if (handleNodeTypeArtifactsRes.isRight()) {
788 return Either.right(handleNodeTypeArtifactsRes.right()
793 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
794 csarInfo, createdArtifacts,
795 new ArtifactOperationInfo(false, false, operation), shouldLock,
797 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
798 if (createdCsarArtifactsEither.isRight()) {
799 return createdCsarArtifactsEither;
802 resource = createdCsarArtifactsEither.left()
805 return Either.left(resource);
808 private Resource handleResourceGenericType(Resource resource) {
809 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
810 if (resource.shouldGenerateInputs()) {
811 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
813 return genericResource;
816 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
817 final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
819 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
820 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
821 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
824 final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
825 .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
826 final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
827 nodeTypesInfo, oldResource.getName(), csarInfo);
828 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
829 oldResource.getName(), csarInfo.getCsarUUID());
830 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
831 nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
832 } catch (Exception e) {
833 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
834 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
835 log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
837 return nodeTypesArtifactsToHandleRes;
840 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
841 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
842 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
843 ImmutablePair<String, String> vfcToscaNames) {
845 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
846 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
847 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
849 if (!isEmpty(extractedVfcsArtifacts)) {
850 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
851 if (extractedVfcsArtifacts.containsKey(namespace)) {
852 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
854 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
855 } else if (curNodeType != null) {
856 // delete all artifacts if have not received artifacts from
858 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
859 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
860 // delete all informational artifacts
861 artifactsToDelete.addAll(curNodeType.getArtifacts()
864 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
866 // delete all deployment artifacts
867 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
869 if (!artifactsToDelete.isEmpty()) {
870 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
873 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
874 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
878 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
879 String previousVfcToscaName, StorageOperationStatus status) {
880 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
881 log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
883 ResponseFormat responseFormat = componentsUtils
884 .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
885 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
886 AuditingActionEnum.CREATE_RESOURCE);
887 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
888 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
889 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
891 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
896 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
897 List<ArtifactDefinition> extractedArtifacts) {
899 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
901 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
902 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
903 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
904 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
905 artifactsToDelete, collectExistingArtifacts(curNodeType));
906 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
907 } catch (Exception e) {
908 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
909 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
911 return nodeTypeArtifactsToHandle;
914 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
915 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
916 List<ArtifactDefinition> artifactsToDelete) {
917 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
918 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
919 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
920 if (!artifactsToUpload.isEmpty()) {
921 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
923 if (!artifactsToUpdate.isEmpty()) {
924 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
926 if (!artifactsToDelete.isEmpty()) {
927 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
930 return nodeTypeArtifactsToHandle;
933 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
934 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
935 List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
936 if (!existingArtifacts.isEmpty()) {
937 extractedArtifacts.stream()
938 .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
939 artifactsToDelete.addAll(existingArtifacts.values());
943 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
944 List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
945 ArtifactDefinition currNewArtifact) {
946 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
948 .filter(a -> a.getArtifactName()
949 .equals(currNewArtifact.getArtifactName()))
951 if (foundArtifact.isPresent()) {
952 if (foundArtifact.get()
954 .equals(currNewArtifact.getArtifactType())) {
955 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
956 existingArtifacts.remove(foundArtifact.get()
957 .getArtifactLabel());
958 artifactsToUpload.remove(currNewArtifact);
960 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
961 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
962 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
968 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
969 ArtifactDefinition foundArtifact) {
970 if (!foundArtifact.getArtifactChecksum()
971 .equals(currNewArtifact.getArtifactChecksum())) {
972 foundArtifact.setPayload(currNewArtifact.getPayloadData());
973 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
974 foundArtifact.setArtifactChecksum(
975 GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
976 artifactsToUpdate.add(foundArtifact);
980 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
981 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
982 if (curNodeType == null) {
983 return existingArtifacts;
985 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
986 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
988 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
989 existingArtifacts.putAll(curNodeType.getArtifacts()
992 .filter(e -> e.getValue()
993 .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
994 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
996 return existingArtifacts;
1000 * Changes resource life cycle state to checked out
1004 * @param inTransaction
1007 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
1008 Either<Resource, ResponseFormat> checkoutResourceRes;
1010 if (!resource.getComponentMetadataDefinition()
1011 .getMetadataDataDefinition()
1013 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
1015 "************* Going to change life cycle state of resource {} to not certified checked out. ",
1016 resource.getName());
1017 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
1018 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1019 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1020 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
1021 inTransaction, true);
1022 if (checkoutRes.isRight()) {
1023 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
1024 resource.getComponentType()
1026 resource.getUniqueId(), checkoutRes.right()
1029 checkoutResourceRes = Either.right(checkoutRes.right()
1032 checkoutResourceRes = Either.left((Resource) checkoutRes.left()
1036 checkoutResourceRes = Either.left(resource);
1038 } catch (Exception e) {
1039 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1040 checkoutResourceRes = Either.right(responseFormat);
1041 log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
1044 return checkoutResourceRes;
1048 * Handles Artifacts of NodeType
1050 * @param nodeTypeResource
1051 * @param nodeTypeArtifactsToHandle
1053 * @param inTransaction
1056 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
1057 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1058 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
1059 List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
1060 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1061 Either<Resource, ResponseFormat> changeStateResponse;
1063 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1064 if (changeStateResponse.isRight()) {
1065 return Either.right(changeStateResponse.right()
1068 nodeTypeResource = changeStateResponse.left()
1071 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1072 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1073 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1075 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1076 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1077 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1078 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
1079 nodeTypeResource.getName());
1080 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1081 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
1082 createdArtifacts, new ArtifactOperationInfo(false,
1083 ignoreLifecycleState, curOperation),
1084 false, inTransaction);
1085 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1086 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1088 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1091 if (handleNodeTypeArtifactsRes == null) {
1092 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1094 } catch (Exception e) {
1095 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1096 handleNodeTypeArtifactsRes = Either.right(responseFormat);
1097 log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1099 return handleNodeTypeArtifactsRes;
1102 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
1103 final String vfResourceName,
1104 final CsarInfo csarInfo) {
1105 final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
1107 final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
1108 if (!nodes.isEmpty()) {
1109 final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
1110 while (nodesNameEntry.hasNext()) {
1111 final Entry<String, Object> nodeType = nodesNameEntry.next();
1112 final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
1113 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
1114 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
1117 for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
1118 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
1119 vfResourceName, cvfc.getType()));
1121 return vfcToscaNames;
1124 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1125 Map<String, Object> nodes = new HashMap<>();
1126 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
1127 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
1129 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
1133 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
1134 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1135 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
1136 if (eitherNodeTypes.isLeft()) {
1137 nodes.putAll(eitherNodeTypes.left()
1142 public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
1144 log.trace("************* created successfully from YAML, resource TOSCA ");
1145 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
1146 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
1147 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
1148 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
1149 nodeTypesInfo, csarInfo, resource);
1150 if (findNodeTypesArtifactsToHandleRes.isRight()) {
1151 log.debug("failed to find node types for update with artifacts during import csar {}. ",
1152 csarInfo.getCsarUUID());
1153 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1154 StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
1155 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
1157 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
1158 csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
1161 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
1162 vfResource.getToscaResourceName());
1163 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
1167 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1168 log.trace("validating resource before create");
1169 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
1170 // validate user role
1171 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
1172 // VF / PNF "derivedFrom" should be null (or ignored)
1173 if (ModelConverter.isAtomicComponent(resource)) {
1174 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1176 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1180 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
1181 // nodeTypesArtifactsToCreate, true, false, null
1182 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1183 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1184 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1185 boolean shouldLock, boolean inTransaction, String nodeName) {
1187 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
1188 Resource createdResource;
1190 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
1191 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
1192 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1194 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
1195 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1196 StatusCode.STARTED,"");
1197 createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1198 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
1199 csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1200 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
1201 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1202 StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
1203 } catch (ComponentException e) {
1204 ResponseFormat responseFormat = e.getResponseFormat() == null
1205 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
1206 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1207 AuditingActionEnum.IMPORT_RESOURCE);
1209 } catch (StorageException e) {
1210 ResponseFormat responseFormat = componentsUtils
1211 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1212 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1213 AuditingActionEnum.IMPORT_RESOURCE);
1216 return createdResource;
1220 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
1221 Map<String, Object> mappedToscaTemplate, boolean needLock,
1222 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1223 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1224 CsarInfo csarInfo) {
1226 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1227 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1228 if (toscaVersion.isRight()) {
1229 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1231 Map<String, Object> mapToConvert = new HashMap<>();
1232 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
1234 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1235 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1236 nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1237 return csarInfo.getCreatedNodes();
1240 private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1241 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1243 .orValue(HashMap::new);
1246 private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1247 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1248 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1249 CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1250 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
1252 Resource vfcCreated = null;
1253 while (nodesNameValueIter.hasNext()) {
1254 Entry<String, Object> nodeType = nodesNameValueIter.next();
1255 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1256 || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1258 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1259 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1260 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1261 nodeTypesInfo, csarInfo, nodeType.getKey());
1262 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1263 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1264 && !csarInfo.getCreatedNodesToscaResourceNames()
1265 .containsKey(nodeType.getKey())) {
1266 log.trace("************* Going to create node {}", nodeType.getKey());
1267 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
1268 nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
1269 nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1270 log.debug("************* Finished to create node {}", nodeType.getKey());
1272 vfcCreated = resourceCreated.getLeft();
1273 csarInfo.getCreatedNodesToscaResourceNames()
1274 .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1276 if (vfcCreated != null) {
1277 csarInfo.getCreatedNodes()
1278 .put(nodeType.getKey(), vfcCreated);
1280 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1284 private Resource handleNestedVfc(Resource resource,
1285 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1286 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1289 String yamlName = nodesInfo.get(nodeName)
1290 .getTemplateFileName();
1291 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
1292 .getMappedToscaTemplate();
1294 log.debug("************* Going to create node types from yaml {}", yamlName);
1295 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
1296 createdArtifacts, nodesInfo, csarInfo);
1297 log.debug("************* Finished to create node types from yaml {}", yamlName);
1299 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1300 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1301 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
1302 nodeName, yamlName);
1307 private Resource handleComplexVfc(final Resource resource,
1308 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
1309 nodesArtifactsToHandle,
1310 final List<ArtifactDefinition>
1311 createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1312 final String nodeName, final String yamlName) {
1314 Resource oldComplexVfc = null;
1315 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1316 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1317 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1318 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1319 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1320 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1322 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1323 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1324 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1325 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1326 } else if (oldComplexVfcRes.isLeft()) {
1327 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1328 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1329 oldComplexVfcRes.left().value(),
1330 newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1331 if (eitherValidation.isLeft()) {
1332 oldComplexVfc = oldComplexVfcRes.left().value();
1335 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
1336 yamlName, oldComplexVfc, newComplexVfc);
1337 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1338 final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1339 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1340 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1341 final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
1342 lifecycleChangeInfo, true, false, true);
1343 csarInfo.getCreatedNodes().put(nodeName, result);
1344 csarInfo.removeNodeFromQueue();
1348 private Resource handleComplexVfc(
1349 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1350 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1351 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1353 Resource handleComplexVfcRes;
1354 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
1355 .getMappedToscaTemplate();
1356 String yamlContent = new String(csarInfo.getCsar()
1358 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
1360 .collect(toMap(Entry::getKey, e -> e.getValue()
1361 .getUnmarkedCopy()));
1362 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1363 if (oldComplexVfc == null) {
1364 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1365 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1367 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1368 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1369 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1371 return handleComplexVfcRes;
1374 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1375 Map<String, NodeTypeInfo> nodesInfo) {
1377 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1378 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1379 csarInfo.addNodeToQueue(nodeName);
1380 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
1384 private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
1386 final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
1387 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1388 final String resourceType = findTypes[0];
1389 return nameWithouNamespacePrefix.substring(resourceType.length());
1392 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
1393 final Entry<String, Object> nodeNameValue,
1395 final Map<String, Object> mapToConvert,
1396 final Resource resourceVf,
1397 final boolean needLock,
1398 final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1399 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1400 final boolean forceCertificationAllowed,
1401 final CsarInfo csarInfo,
1402 final boolean isNested) {
1404 final UploadResourceInfo resourceMetaData = fillResourceMetadata(
1405 yamlName, resourceVf, nodeNameValue.getKey(), user);
1407 final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1408 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1409 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1410 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1411 nodeNameValue.getKey(), isNested);
1414 private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
1415 final Map<String, Object> mapToConvert,
1416 final String nodeResourceType,
1417 final CsarInfo csarInfo) {
1418 // We need to create a Yaml from each node_types in order to create
1419 // resource from each node type using import normative flow.
1420 final DumperOptions options = new DumperOptions();
1421 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1422 final Yaml yaml = new Yaml(options);
1424 final Map<String, Object> node = new HashMap<>();
1425 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1426 .getLeft(), nodeNameValue.getValue());
1427 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1429 return yaml.dumpAsMap(mapToConvert);
1432 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1433 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1437 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
1438 UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1439 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1440 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1441 String nodeName, boolean isNested) {
1443 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1444 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1445 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1447 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1448 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1449 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1453 * Validates if a given node type name has a valid prefix.
1455 * @param nodeName node name from definition file
1456 * @param definedResourceNamespaceList is a list of all node type name prefix allowed
1457 * @return a valid node type name prefix if it`s found
1459 public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
1460 final List<String> definedResourceNamespaceList) {
1461 for (final String validNamespace : definedResourceNamespaceList) {
1462 if (nodeName.startsWith(validNamespace)) {
1463 return Optional.of(validNamespace);
1466 return Optional.empty();
1469 private List<String> getDefinedNodeTypeNamespaceList() {
1470 return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
1473 private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
1474 final String nodeName, final User user) {
1476 final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1478 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
1479 log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
1481 if (!nodeName.startsWith(nodeTypeNamePrefix)) {
1482 log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
1483 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1484 resourceMetaData.getName(), nodeName);
1487 final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
1488 final String namePrefix = nodeName.replace(actualName, "");
1489 String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
1490 log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
1491 resourceType, nodeName, actualName, nodeTypeNamePrefix);
1493 // if we import from csar, the node_type name can be
1494 // org.openecomp.resource.abstract.node_name - in this case we always
1496 if (resourceType.equals(Constants.ABSTRACT)) {
1497 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1500 if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
1501 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1505 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1506 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
1507 resourceType.toUpperCase(), ResourceTypeEnum.values());
1508 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1509 resourceMetaData.getName(), nodeName);
1513 resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
1515 // Setting type from name
1516 final String type = resourceType.toUpperCase();
1517 resourceMetaData.setResourceType(type);
1519 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1520 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1521 resourceMetaData.setContactId(user.getUserId());
1522 resourceMetaData.setVendorName(resourceVf.getVendorName());
1523 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1526 final List<String> tags = new ArrayList<>();
1527 tags.add(resourceMetaData.getName());
1528 resourceMetaData.setTags(tags);
1531 final CategoryDefinition category = new CategoryDefinition();
1532 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1533 final SubCategoryDefinition subCategory = new SubCategoryDefinition();
1534 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1535 category.addSubCategory(subCategory);
1536 final List<CategoryDefinition> categories = new ArrayList<>();
1537 categories.add(category);
1538 resourceMetaData.setCategories(categories);
1540 return resourceMetaData;
1543 private Resource buildComplexVfcMetadata(final Resource resourceVf,
1544 final CsarInfo csarInfo,
1545 final String nodeName,
1546 final Map<String, NodeTypeInfo> nodesInfo) {
1547 final Resource cvfc = new Resource();
1548 final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1549 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1550 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1551 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1552 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1553 cvfc.setAbstract(true);
1554 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1555 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1556 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1557 cvfc.setContactId(csarInfo.getModifier()
1559 cvfc.setCreatorUserId(csarInfo.getModifier()
1561 cvfc.setVendorName(resourceVf.getVendorName());
1562 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1563 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1564 cvfc.setToscaResourceName(buildNestedToscaResourceName(
1565 ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1566 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1568 final List<String> tags = new ArrayList<>();
1569 tags.add(cvfc.getName());
1572 final CategoryDefinition category = new CategoryDefinition();
1573 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1574 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1575 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1576 category.addSubCategory(subCategory);
1577 final List<CategoryDefinition> categories = new ArrayList<>();
1578 categories.add(category);
1579 cvfc.setCategories(categories);
1581 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1582 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1583 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1588 private String buildCvfcName(final String resourceVfName, final String nodeName) {
1590 String nameWithouNamespacePrefix =
1591 nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1592 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1593 String resourceType = findTypes[0];
1594 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1595 return addCvfcSuffixToResourceName(resourceName);
1598 private Resource createResourceAndRIsFromYaml(final String yamlName,
1600 final ParsedToscaYamlInfo parsedToscaYamlInfo,
1601 final AuditingActionEnum actionEnum,
1602 final boolean isNormative,
1603 final List<ArtifactDefinition> createdArtifacts,
1604 final String topologyTemplateYaml,
1605 final Map<String, NodeTypeInfo> nodeTypesInfo,
1606 final CsarInfo csarInfo,
1607 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1608 final boolean shouldLock,
1609 final boolean inTransaction,
1610 final String nodeName) {
1612 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1615 final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1617 if (lockResult.isRight()) {
1618 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1619 throw new ByResponseFormatComponentException(lockResult.right().value());
1621 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1624 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1625 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
1626 final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1627 resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
1628 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1629 log.trace("************* Going to add inputs from yaml {}", yamlName);
1630 if (resource.shouldGenerateInputs())
1631 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1633 final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1634 resource = createInputsOnResource(resource, inputs);
1635 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1636 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
1637 resource.getComponentMetadataForSupportLog(),
1638 StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
1639 if (resource.getResourceType() == ResourceTypeEnum.PNF) {
1640 log.trace("************* Adding generic properties to PNF");
1641 resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
1642 genericResource.getProperties());
1643 log.trace("************* Adding software information to PNF");
1644 softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
1645 log.trace("************* Removing non-mano software information file from PNF");
1646 if (csarInfo.getSoftwareInformationPath().isPresent() &&
1647 !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
1648 log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
1649 "catalog-be", "Could not remove the software information file.");
1653 final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1655 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1656 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName);
1657 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1658 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
1660 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1661 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
1662 resource.getComponentMetadataForSupportLog(),
1663 StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName);
1664 // validate update vf module group names
1665 final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1666 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1667 if (validateUpdateVfGroupNamesRes.isRight()) {
1668 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1669 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1671 // add groups to resource
1672 final Map<String, GroupDefinition> groups;
1673 log.trace("************* Going to add groups from yaml {}", yamlName);
1674 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
1675 StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
1676 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1677 groups = validateUpdateVfGroupNamesRes.left().value();
1679 groups = parsedToscaYamlInfo.getGroups();
1682 final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
1683 if (createGroupsOnResource.isRight()) {
1684 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1685 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1686 resource.getComponentMetadataForSupportLog(),
1687 StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
1688 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1690 resource = createGroupsOnResource.left().value();
1691 log.trace("************* Finished to add groups from yaml {}", yamlName);
1692 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1693 resource.getComponentMetadataForSupportLog(),
1694 StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
1695 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1696 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1697 resource.getComponentMetadataForSupportLog(),
1698 StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
1700 log.trace("************* Starting to add policies from yaml {}", yamlName);
1701 Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
1702 if (MapUtils.isNotEmpty(policies)) {
1703 resource = createPoliciesOnResource(resource, policies);
1705 log.trace("************* Finished to add policies from yaml {}", yamlName);
1707 final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
1708 new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
1710 final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
1711 ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
1712 nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1713 if (createArtifactsEither.isRight()) {
1714 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1715 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1716 resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
1717 createArtifactsEither.right().value());
1718 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1720 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1721 resource.getComponentMetadataForSupportLog(),
1722 StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
1723 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1724 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1725 ASDCKpiApi.countCreatedResourcesKPI();
1728 } catch (final ComponentException | StorageException e) {
1729 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1731 } catch (final ToscaOperationException e) {
1732 log.error("An error has occurred during resource and resource instance creation", e);
1733 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1734 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
1735 "catalog-be", e.getMessage());
1736 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1737 } catch (final BusinessLogicException e) {
1738 log.error("An error has occurred during resource and resource instance creation", e);
1739 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1740 throw new ByResponseFormatComponentException(e.getResponseFormat());
1742 if (!inTransaction) {
1743 janusGraphDao.commit();
1746 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1747 NodeTypeEnum.Resource);
1752 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1753 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1754 if (!inTransaction) {
1755 janusGraphDao.rollback();
1757 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1758 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1759 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
1760 resource.getName());
1764 private Resource getResourceWithGroups(String resourceId) {
1766 ComponentParametersView filter = new ComponentParametersView();
1767 filter.setIgnoreGroups(false);
1768 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
1770 if (updatedResource.isRight()) {
1771 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
1772 .value()), resourceId);
1774 return updatedResource.left()
1778 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1779 Map<String, GroupDefinition> groups) {
1780 if (groups != null && !groups.isEmpty()) {
1781 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1782 handleGroupsProperties(resource, groups);
1783 fillGroupsFinalFields(groupsAsList);
1784 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1785 groupsAsList, true);
1786 if (createGroups.isRight()) {
1787 return Either.right(createGroups.right()
1791 return Either.left(resource);
1794 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1795 List<InputDefinition> inputs = resource.getInputs();
1796 if (MapUtils.isNotEmpty(groups)) {
1799 .filter(g -> isNotEmpty(g.getProperties()))
1800 .flatMap(g -> g.getProperties()
1802 .forEach(p -> handleGetInputs(p, inputs));
1806 private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
1807 policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
1811 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1812 if (isNotEmpty(property.getGetInputValues())) {
1813 if (inputs == null || inputs.isEmpty()) {
1814 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1815 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1817 .map(GetInputValueDataDefinition::getInputName)
1821 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
1823 while (getInputValuesIter.hasNext()) {
1824 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1825 InputDefinition input = findInputByName(inputs, getInput);
1826 getInput.setInputId(input.getUniqueId());
1827 if (getInput.getGetInputIndex() != null) {
1828 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1829 input = findInputByName(inputs, getInputIndex);
1830 getInputIndex.setInputId(input.getUniqueId());
1831 getInputValuesIter.add(getInputIndex);
1837 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1839 final String inputName = getInput != null ? getInput.getInputName() : "";
1841 if(inputs == null || inputs.isEmpty()) {
1842 log.debug("#findInputByName - Inputs list is empty");
1843 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, inputName);
1846 Optional<InputDefinition> inputOpt = inputs.stream()
1847 .filter(p -> p.getName()
1850 if (!inputOpt.isPresent()) {
1851 log.debug("#findInputByName - Failed to find the input {} ", inputName);
1852 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, inputName);
1854 return inputOpt.get();
1857 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1858 groupsAsList.forEach(groupDefinition -> {
1859 groupDefinition.setInvariantName(groupDefinition.getName());
1860 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1864 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1865 if (isEmpty(groups)) {
1868 return updateOrCreateGroups(resource, groups);
1871 private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1872 List<GroupDefinition> groupsFromResource = resource.getGroups();
1873 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1874 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1875 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1876 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1877 if (isNotEmpty(groupsFromResource)) {
1878 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1879 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1881 groupsToCreate.addAll(groupsAsList);
1883 if (isNotEmpty(groupsToCreate)) {
1884 fillGroupsFinalFields(groupsToCreate);
1885 if (isNotEmpty(groupsFromResource)) {
1886 groupBusinessLogic.addGroups(resource, groupsToCreate, true)
1888 .on(this::throwComponentException);
1890 groupBusinessLogic.createGroups(resource, groupsToCreate, true)
1892 .on(this::throwComponentException);
1895 if (isNotEmpty(groupsToDelete)) {
1896 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1898 .on(this::throwComponentException);
1900 if (isNotEmpty(groupsToUpdate)) {
1901 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1903 .on(this::throwComponentException);
1909 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1910 List<GroupDefinition> groupsToDelete) {
1911 for (GroupDefinition group : groupsFromResource) {
1912 Optional<GroupDefinition> op = groupsAsList.stream()
1913 .filter(p -> p.getInvariantName()
1914 .equalsIgnoreCase(group.getInvariantName()))
1916 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
1918 groupsToDelete.add(group);
1923 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1924 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1925 for (GroupDefinition group : groupsAsList) {
1926 Optional<GroupDefinition> op = groupsFromResource.stream()
1927 .filter(p -> p.getInvariantName()
1928 .equalsIgnoreCase(group.getInvariantName()))
1930 if (op.isPresent()) {
1931 GroupDefinition groupToUpdate = op.get();
1932 groupToUpdate.setMembers(group.getMembers());
1933 groupToUpdate.setCapabilities(group.getCapabilities());
1934 groupToUpdate.setProperties(group.getProperties());
1935 groupsToUpdate.add(groupToUpdate);
1937 groupsToCreate.add(group);
1942 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1943 List<InputDefinition> resourceProperties = resource.getInputs();
1944 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1946 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1948 if (createInputs.isRight()) {
1949 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
1950 StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
1952 throw new ByResponseFormatComponentException(createInputs.right()
1955 resource.setInputs(createInputs.left().value());
1960 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
1961 Resource component) {
1963 List<GroupDefinition> result = new ArrayList<>();
1964 List<ComponentInstance> componentInstances = component.getComponentInstances();
1966 if (groups != null) {
1967 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1968 if (validateCyclicGroupsDependencies.isRight()) {
1969 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
1971 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1972 String groupName = entry.getKey();
1973 GroupDefinition groupDefinition = entry.getValue();
1974 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1975 updatedGroupDefinition.setMembers(null);
1976 Map<String, String> members = groupDefinition.getMembers();
1977 if (members != null) {
1978 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
1981 result.add(updatedGroupDefinition);
1987 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
1988 Resource component, List<ComponentInstance> componentInstances, String groupName,
1989 Map<String, String> members) {
1990 Set<String> compInstancesNames = members.keySet();
1992 if (CollectionUtils.isEmpty(componentInstances)) {
1993 String membersAstString = compInstancesNames.stream()
1994 .collect(joining(","));
1996 "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1997 membersAstString, groupName, component.getNormalizedName());
1998 throw new ByActionStatusComponentException(
1999 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2000 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2002 // Find all component instances with the member names
2003 Map<String, String> memberNames = componentInstances.stream()
2004 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2005 memberNames.putAll(groups.keySet()
2007 .collect(toMap(g -> g, g -> "")));
2008 Map<String, String> relevantInstances = memberNames.entrySet()
2010 .filter(n -> compInstancesNames.contains(n.getKey()))
2011 .collect(toMap(Entry::getKey, Entry::getValue));
2013 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2015 List<String> foundMembers = new ArrayList<>();
2016 if (relevantInstances != null) {
2017 foundMembers = relevantInstances.keySet()
2021 compInstancesNames.removeAll(foundMembers);
2022 String membersAstString = compInstancesNames.stream()
2023 .collect(joining(","));
2024 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
2025 component.getNormalizedName());
2026 throw new ByActionStatusComponentException(
2027 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2028 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2030 updatedGroupDefinition.setMembers(relevantInstances);
2034 * This Method validates that there is no cyclic group dependencies. meaning
2035 * group A as member in group B which is member in group A
2040 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
2042 Either<Boolean, ResponseFormat> result = Either.left(true);
2044 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
2046 while (allGroupsItr.hasNext() && result.isLeft()) {
2047 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
2048 // Fetches a group member A
2049 String groupAName = groupAEntry.getKey();
2050 // Finds all group members in group A
2051 Set<String> allGroupAMembersNames = new HashSet<>();
2052 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
2053 // If A is a group member of itself found cyclic dependency
2054 if (allGroupAMembersNames.contains(groupAName)) {
2055 ResponseFormat responseFormat = componentsUtils
2056 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
2057 result = Either.right(responseFormat);
2060 } catch (Exception e) {
2061 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2062 result = Either.right(responseFormat);
2063 log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
2069 * This Method fills recursively the set groupMembers with all the members
2070 * of the given group which are also of type group.
2074 * @param allGroupMembers
2077 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
2078 Set<String> allGroupMembers) {
2080 // Found Cyclic dependency
2081 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
2084 GroupDefinition groupDefinition = allGroups.get(groupName);
2085 // All Members Of Current Group Resource Instances & Other Groups
2086 Set<String> currGroupMembers = groupDefinition.getMembers()
2088 // Filtered Members Of Current Group containing only members which
2090 List<String> currGroupFilteredMembers = currGroupMembers.stream()
2092 // Keep Only Elements of type group and not Resource Instances
2093 filter(allGroups::containsKey)
2095 // Add Filtered Elements to main Set
2096 peek(allGroupMembers::add)
2101 // Recursively call the method for all the filtered group members
2102 for (String innerGroupName : currGroupFilteredMembers) {
2103 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
2108 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
2109 Set<String> allGroupMembers) {
2111 boolean stop = false;
2112 // In Case Not Group Stop
2113 if (!allGroups.containsKey(groupName)) {
2116 // In Case Group Has no members stop
2118 GroupDefinition groupDefinition = allGroups.get(groupName);
2119 stop = isEmpty(groupDefinition.getMembers());
2122 // In Case all group members already contained stop
2124 final Set<String> allMembers = allGroups.get(groupName)
2127 Set<String> membersOfTypeGroup = allMembers.stream()
2129 // Filter In Only Group members
2130 filter(allGroups::containsKey)
2134 stop = allGroupMembers.containsAll(membersOfTypeGroup);
2139 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
2140 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
2141 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2143 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2146 log.debug("************* Going to create all nodes {}", yamlName);
2147 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
2148 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
2149 log.debug("************* Finished to create all nodes {}", yamlName);
2150 log.debug("************* Going to create all resource instances {}", yamlName);
2151 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
2152 resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
2153 csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
2154 log.debug("************* Finished to create all resource instances {}", yamlName);
2155 log.debug("************* Going to create all relations {}", yamlName);
2156 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
2157 log.debug("************* Finished to create all relations {}", yamlName);
2158 log.debug("************* Going to create positions {}", yamlName);
2159 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
2161 log.debug("************* Finished to set positions {}", yamlName);
2165 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
2166 List<ArtifactDefinition> artifactsToAdd) {
2167 List<String> vfcArtifactNames = vfcArtifacts.stream()
2168 .map(ArtifactDataDefinition::getArtifactName)
2170 artifactsToAdd.stream()
2172 if (!vfcArtifactNames.contains(a.getArtifactName())) {
2173 vfcArtifacts.add(a);
2175 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
2181 @SuppressWarnings("unchecked")
2182 private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
2183 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2184 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2185 CsarInfo csarInfo, String nodeName) {
2187 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2188 if (nodeTypeEntry.getValue()
2191 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
2192 csarInfo, nodeTypeEntry.getKey());
2193 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2196 Map<String, Object> mappedToscaTemplate = null;
2197 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
2198 mappedToscaTemplate = nodeTypesInfo.get(nodeName)
2199 .getMappedToscaTemplate();
2201 if (isEmpty(mappedToscaTemplate)) {
2202 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2204 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
2205 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2206 } catch (ComponentException e) {
2207 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
2208 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
2209 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2210 AuditingActionEnum.IMPORT_RESOURCE);
2212 } catch (StorageException e) {
2213 ResponseFormat responseFormat = componentsUtils
2214 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2215 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2216 AuditingActionEnum.IMPORT_RESOURCE);
2221 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
2222 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
2223 boolean inTransaction) {
2225 if (csarInfo.getCsar() != null) {
2226 String vendorLicenseModelId = null;
2227 String vfLicenseModelId = null;
2229 if (artifactOperation.isUpdate()) {
2230 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
2231 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
2232 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
2233 if (artifactEntry.getValue()
2235 .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
2236 vendorLicenseModelId = artifactEntry.getValue()
2239 if (artifactEntry.getValue()
2241 .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
2242 vfLicenseModelId = artifactEntry.getValue()
2249 // Specific Behavior for license artifacts
2250 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2251 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
2252 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
2253 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
2254 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
2255 shouldLock, inTransaction);
2256 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2257 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
2258 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
2259 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
2260 artifactOperation, null, true, shouldLock, inTransaction);
2262 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
2263 createdArtifacts, shouldLock, inTransaction, artifactOperation);
2264 if (eitherCreateResult.isRight()) {
2265 return Either.right(eitherCreateResult.right()
2269 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
2270 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
2272 if (artifacsMetaCsarStatus.isLeft()) {
2273 String artifactsFileName = artifacsMetaCsarStatus.left()
2276 String artifactsContents = artifacsMetaCsarStatus.left()
2279 Either<Resource, ResponseFormat> createArtifactsFromCsar;
2280 if (artifactOperation.isCreateOrLink()) {
2281 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
2282 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
2284 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
2285 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
2289 if (createArtifactsFromCsar.isRight()) {
2290 log.debug("Couldn't create artifacts from artifacts.meta");
2291 return Either.right(createArtifactsFromCsar.right()
2295 return Either.left(createArtifactsFromCsar.left()
2299 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
2304 return Either.left(resource);
2307 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
2308 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
2309 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
2310 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
2311 boolean shouldLock, boolean inTransaction) {
2312 byte[] artifactFileBytes = null;
2314 if (csarInfo.getCsar()
2315 .containsKey(artifactPath)) {
2316 artifactFileBytes = csarInfo.getCsar()
2319 Either<Boolean, ResponseFormat> result = Either.left(true);
2320 if (operation.isUpdate() || operation.isDelete()) {
2321 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
2322 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic
2323 .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
2324 AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, shouldLock,
2326 if (handleDelete.isRight()) {
2327 result = Either.right(handleDelete.right()
2330 Either<ArtifactDefinition, Operation> value = handleDelete.left().value();
2331 if (value.isLeft()) {
2332 String updatedArtifactId = value.left().value().getUniqueId();
2333 if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2334 resource.getDeploymentArtifacts().remove(updatedArtifactId);
2336 resource.getArtifacts().remove(updatedArtifactId);
2343 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2344 operation = new ArtifactOperationInfo(false, false,
2345 ArtifactOperationEnum.CREATE);
2349 if (artifactFileBytes != null) {
2350 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
2351 artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
2352 artifactDescription, artifactFileBytes, null, isFromCsar);
2353 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
2354 .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
2356 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2357 if (eitherNonMetaArtifacts.isRight()) {
2358 BeEcompErrorManager.getInstance()
2359 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2360 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2361 ErrorSeverity.WARNING);
2362 return Either.right(eitherNonMetaArtifacts.right()
2365 ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
2366 createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
2372 private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
2373 if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
2374 resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
2376 resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
2380 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2381 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2384 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2385 List<ArtifactDefinition> createdArtifacts,
2386 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2387 if (operation.isCreateOrLink() && createdArtifacts != null
2388 && eitherNonMetaArtifacts.isLeft()) {
2389 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
2391 if (eitherResult.isLeft()) {
2392 createdArtifacts.add(eitherResult.left()
2398 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2399 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2400 ArtifactOperationInfo artifactOperation) {
2402 Either<Resource, ResponseFormat> resStatus = null;
2403 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2406 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
2407 collectedWarningMessages);
2408 if (artifactPathAndNameList.isRight()) {
2409 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2410 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
2413 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2415 if (artifactOperation.isCreateOrLink()) {
2416 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2417 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
2420 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2421 resource, artifactPathAndNameList.left()
2423 csarInfo.getModifier());
2425 if (findVfCsarArtifactsToHandleRes.isRight()) {
2426 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
2429 if (resStatus == null) {
2430 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
2434 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2435 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
2436 resStatus, vfCsarArtifactsToHandle);
2438 if (resStatus == null) {
2439 resStatus = Either.left(resource);
2441 } catch (Exception e) {
2442 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2443 log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2445 CsarUtils.handleWarningMessages(collectedWarningMessages);
2450 private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
2451 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2452 Either<Resource, ResponseFormat> resStatus,
2453 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2454 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2457 Optional<ResponseFormat> optionalCreateInDBError =
2458 // Stream of artifacts to be created
2459 currArtifactOperationPair.getValue()
2461 // create each artifact
2462 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2463 e.getArtifactName(), e.getArtifactType(),
2464 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2465 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2466 new ArtifactOperationInfo(false, false,
2467 currArtifactOperationPair.getKey()),
2468 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2469 // filter in only error
2470 .filter(Either::isRight)
2472 // Convert the error from either to
2477 // Check if an error occurred
2479 // Error found on artifact Creation
2480 if (optionalCreateInDBError.isPresent()) {
2481 resStatus = Either.right(optionalCreateInDBError.get());
2488 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
2489 Map<String, Set<List<String>>> collectedWarningMessages) {
2490 List<NonMetaArtifactInfo> artifactPathAndNameList =
2491 // Stream of file paths contained in csar
2495 // Filter in only VF artifact path location
2496 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
2497 .matcher(e.getKey())
2499 // Validate and add warnings
2500 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2501 // Filter in Non Warnings
2502 .filter(Either::isLeft)
2503 // Convert from Either to NonMetaArtifactInfo
2508 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2509 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2510 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
2512 return Either.right(nonMetaArtifactInfo.getArtifactName());
2515 return Either.left(artifactPathAndNameList);
2518 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2519 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2521 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2522 // collect all Deployment and Informational artifacts of VF
2523 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
2525 existingArtifacts.addAll(resource.getDeploymentArtifacts()
2528 if (resource.getArtifacts() != null && !resource.getArtifacts()
2530 existingArtifacts.addAll(resource.getArtifacts()
2533 existingArtifacts = existingArtifacts.stream()
2534 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2535 // was created from HEAT.meta
2536 .filter(this::isNonMetaArtifact)
2539 List<String> artifactsToIgnore = new ArrayList<>();
2540 // collect IDs of Artifacts of VF which belongs to any group
2541 if (resource.getGroups() != null) {
2542 resource.getGroups()
2545 if (g.getArtifacts() != null && !g.getArtifacts()
2547 artifactsToIgnore.addAll(g.getArtifacts());
2551 existingArtifacts = existingArtifacts.stream()
2552 // filter artifacts which belongs to any group
2553 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
2555 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2558 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2559 boolean result = true;
2560 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2566 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2567 boolean result = true;
2568 if (artifact.getArtifactType() == null
2569 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2570 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2576 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
2577 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
2578 log.debug("#createResourceInstancesRelations - Going to create relations ");
2579 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations");
2580 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2581 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
2582 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
2584 "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
2585 resource.getUniqueId(), yamlName);
2586 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
2587 BeEcompErrorManager.getInstance()
2588 .logInternalDataError("createResourceInstancesRelations",
2589 "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2590 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2592 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2593 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2594 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2595 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2596 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2597 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2598 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2599 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2601 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2602 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2603 if (allDataTypes.isRight()) {
2604 JanusGraphOperationStatus status = allDataTypes.right()
2606 BeEcompErrorManager.getInstance()
2607 .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2608 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2609 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2610 StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
2611 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2612 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
2615 Resource finalResource = resource;
2616 uploadResInstancesMap.values()
2617 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2618 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
2619 instAttributes, existingNodeTypesByResourceNames, instInputs, i));
2620 resource.getComponentInstances()
2622 .filter(i -> !i.isCreatedFromCsar())
2623 .forEach(i->processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
2625 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2626 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2627 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2628 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2629 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2630 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2631 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2632 associateResourceInstances(yamlName, resource, relations);
2633 handleSubstitutionMappings(resource, uploadResInstancesMap);
2634 log.debug("************* in create relations, getResource start");
2635 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations");
2636 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2637 .getToscaFullElement(resource.getUniqueId());
2638 log.debug("************* in create relations, getResource end");
2639 if (eitherGetResource.isRight()) {
2640 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2641 StatusCode.ERROR,"ERROR while create relations");
2642 throw new ByResponseFormatComponentException(componentsUtils
2643 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
2644 .value()), resource));
2646 return eitherGetResource.left()
2650 private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
2651 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2652 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2653 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2654 Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, List<ComponentInstanceInput>> instInputs, Map<String, List<PropertyDefinition>> instAttributes) {
2655 Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
2656 if(foundInstance.isPresent()){
2657 if(MapUtils.isNotEmpty(foundInstance.get().getCapabilities())){
2658 instCapabilities.put(instance, foundInstance.get().getCapabilities());
2660 if(MapUtils.isNotEmpty(foundInstance.get().getRequirements())){
2661 instRequirements.put(instance, foundInstance.get().getRequirements());
2663 if(MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())){
2664 instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
2666 if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
2667 instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
2669 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
2670 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))){
2671 instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
2673 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
2674 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))){
2675 instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
2677 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
2678 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
2679 instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(PropertyDefinition::new).collect(toList()));
2684 private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
2685 if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
2686 return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
2688 return Optional.empty();
2691 private void associateResourceInstances(String yamlName, Resource resource,
2692 List<RequirementCapabilityRelDef> relations) {
2693 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2695 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2696 StorageOperationStatus status = relationsEither.right().value();
2697 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2699 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
2701 setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
2705 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2706 Map<String, List<PropertyDefinition>> instAttributes) {
2707 StorageOperationStatus addArtToInst;
2708 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2710 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2711 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2713 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2717 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2718 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2719 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2720 StorageOperationStatus addArtToInst;
2721 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2723 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2724 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2726 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2730 private void associateArtifactsToInstances(String yamlName, Resource resource,
2731 Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2732 StorageOperationStatus addArtToInst;
2734 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2735 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2736 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2737 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2741 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2742 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2743 StorageOperationStatus addArtToInst = toscaOperationFacade
2744 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2745 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2746 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2747 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2751 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2752 Map<String, List<ComponentInstanceInput>> instInputs) {
2753 if (MapUtils.isNotEmpty(instInputs)) {
2754 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2755 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2756 if (addInputToInst.isRight()) {
2758 StorageOperationStatus addInputToInstError = addInputToInst.right().value();
2759 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2760 addInputToInstError);
2761 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
2763 setComponentInstanceInputsOnComponent(resource, instInputs);
2767 private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2768 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
2769 if (componentInstancesInputs == null)
2770 componentInstancesInputs = new HashMap<>();
2771 componentInstancesInputs.putAll(instInputs);
2772 resource.setComponentInstancesInputs(componentInstancesInputs);
2775 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2776 Map<String, List<ComponentInstanceProperty>> instProperties) {
2777 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2778 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2779 if (addPropToInst.isRight()) {
2780 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2781 StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
2782 StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
2783 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2784 storageOperationStatus);
2785 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
2787 setComponentInstancePropertiesOnComponent(resource, instProperties);
2790 private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2791 Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
2792 if (componentInstanceProps == null )
2793 componentInstanceProps = new HashMap<>();
2794 componentInstanceProps.putAll(instProperties);
2795 resource.setComponentInstancesProperties(componentInstanceProps);
2798 private void handleSubstitutionMappings(Resource resource,
2799 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2800 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2801 Either<Resource, StorageOperationStatus> getResourceRes =
2802 updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
2803 if (getResourceRes.isRight()) {
2804 ResponseFormat responseFormat = componentsUtils
2805 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
2806 .value()), resource);
2807 throw new ByResponseFormatComponentException(responseFormat);
2812 private void addRelationsToRI(String yamlName, Resource resource,
2813 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2814 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2815 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2816 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2817 ComponentInstance currentCompInstance = null;
2818 for (ComponentInstance compInstance : componentInstancesList) {
2820 if (compInstance.getName()
2821 .equals(uploadComponentInstanceInfo.getName())) {
2822 currentCompInstance = compInstance;
2827 if (currentCompInstance == null) {
2828 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2829 resource.getUniqueId());
2830 BeEcompErrorManager.getInstance()
2831 .logInternalDataError(
2832 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2833 resource.getUniqueId(), ErrorSeverity.ERROR);
2834 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2837 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2838 if (addRelationToRiRes.getStatus() != 200) {
2839 throw new ByResponseFormatComponentException(addRelationToRiRes);
2845 private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
2846 if (resource.getComponentInstancesRelations() != null) {
2847 resource.getComponentInstancesRelations().addAll(relations);
2849 resource.setComponentInstancesRelations(relations);
2853 private void processComponentInstance(String yamlName, Resource resource,
2854 List<ComponentInstance> componentInstancesList,
2855 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2856 Map<String, List<ComponentInstanceProperty>> instProperties,
2857 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2858 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2859 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2860 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
2861 Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap,
2862 Map<String, List<ComponentInstanceInput>> instInputs,
2863 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2864 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2865 .filter(i -> i.getName()
2866 .equals(uploadComponentInstanceInfo.getName()))
2868 if (!currentCompInstanceOpt.isPresent()) {
2869 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2870 resource.getUniqueId());
2871 BeEcompErrorManager.getInstance()
2872 .logInternalDataError(
2873 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2874 resource.getUniqueId(), ErrorSeverity.ERROR);
2875 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2877 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2878 String resourceInstanceId = currentCompInstance.getUniqueId();
2879 Resource originResource = getOriginResource(originCompMap, currentCompInstance);
2880 if (isNotEmpty(originResource.getRequirements())) {
2881 instRequirements.put(currentCompInstance, originResource.getRequirements());
2883 if (isNotEmpty(originResource.getCapabilities())) {
2884 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2885 currentCompInstance, originResource);
2887 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
2889 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2891 if (originResource.getArtifacts() != null && !originResource.getArtifacts()
2893 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2895 if (originResource.getAttributes() != null && !originResource.getAttributes()
2897 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2899 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2900 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2901 originResource, currentCompInstance, instProperties, allDataTypes.left()
2903 if (addPropertiesValueToRiRes.getStatus() != 200) {
2904 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2907 addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
2913 private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2914 Resource originResource;
2915 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2916 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2917 .getToscaFullElement(currentCompInstance.getComponentUid());
2918 if (getOriginResourceRes.isRight()) {
2919 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2920 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2921 getOriginResourceRes);
2922 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
2923 .value()), currentCompInstance.getComponentUid());
2925 originResource = getOriginResourceRes.left()
2927 originCompMap.put(originResource.getUniqueId(), originResource);
2929 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2931 return originResource;
2934 private void processComponentInstanceCapabilities(
2935 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2936 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2937 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2938 Resource originResource) {
2939 Map<String, List<CapabilityDefinition>> originCapabilities;
2940 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2941 originCapabilities = new HashMap<>();
2942 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2943 originResource.getCapabilities()
2944 .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
2945 uploadComponentInstanceInfo.getCapabilities()
2947 .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
2948 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2950 originCapabilities = originResource.getCapabilities();
2952 instCapabilties.put(currentCompInstance, originCapabilities);
2955 private void updateCapabilityPropertiesValues(
2956 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2957 Map<String, List<CapabilityDefinition>> originCapabilities,
2958 Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2959 originCapabilities.values()
2961 .flatMap(Collection::stream)
2962 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2963 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
2968 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
2969 List<UploadCapInfo> capabilities) {
2970 for (UploadCapInfo capability : capabilities) {
2971 if (isNotEmpty(capability.getProperties())) {
2972 newPropertiesMap.put(capability.getName(), capability.getProperties()
2974 .collect(toMap(UploadInfo::getName, p -> p)));
2979 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
2980 List<CapabilityDefinition> capabilities) {
2981 List<CapabilityDefinition> list = capabilities.stream()
2982 .map(CapabilityDefinition::new)
2984 originCapabilities.put(type, list);
2987 private void updatePropertyValues(List<ComponentInstanceProperty> properties,
2988 Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
2989 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2992 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2993 Map<String, DataTypeDefinition> allDataTypes) {
2994 String value = null;
2995 List<GetInputValueDataDefinition> getInputs = null;
2996 boolean isValidate = true;
2997 if (null != propertyInfo && propertyInfo.getValue() != null) {
2998 getInputs = propertyInfo.getGet_input();
2999 isValidate = getInputs == null || getInputs.isEmpty();
3001 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
3003 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3004 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3007 property.setValue(value);
3008 return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3011 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
3012 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3013 Either<Resource, StorageOperationStatus> updateRes = null;
3014 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3015 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3016 StorageOperationStatus status = toscaOperationFacade
3017 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
3018 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3020 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
3021 resource.getUniqueId(), status);
3022 updateRes = Either.right(status);
3024 if (updateRes == null) {
3025 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
3026 updatedInstCapabilities, updatedInstRequirements);
3027 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
3028 updatedInstRequirements, resource);
3029 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3031 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
3032 resource.getUniqueId(), status);
3033 updateRes = Either.right(status);
3036 if (updateRes == null) {
3037 updateRes = Either.left(resource);
3042 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
3043 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3044 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
3045 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3047 componentInstances.stream()
3049 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
3050 .getCapabilitiesNamesToUpdate());
3051 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
3052 .getRequirementsNamesToUpdate());
3056 private void fillUpdatedInstRequirements(
3057 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
3058 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3059 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3060 Set<String> updatedReqNames = new HashSet<>();
3061 if (isNotEmpty(requirementsNamesToUpdate)) {
3062 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
3064 updatedRequirements.put(requirements.getKey(), requirements.getValue()
3066 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
3067 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3069 r.setParentName(r.getName());
3070 r.setName(requirementsNamesToUpdate.get(r.getName()));
3071 updatedReqNames.add(r.getName());
3074 .collect(toList()));
3077 if (isNotEmpty(updatedRequirements)) {
3078 updatedInstRequirements.put(instance, updatedRequirements);
3082 private void fillUpdatedInstCapabilities(
3083 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
3084 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3085 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3086 Set<String> updatedCapNames = new HashSet<>();
3087 if (isNotEmpty(capabilitiesNamesToUpdate)) {
3088 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
3090 updatedCapabilities.put(requirements.getKey(), requirements.getValue()
3092 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
3093 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3095 c.setParentName(c.getName());
3096 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
3097 updatedCapNames.add(c.getName());
3100 .collect(toList()));
3103 if (isNotEmpty(updatedCapabilities)) {
3104 updatedInstCapabilties.put(instance, updatedCapabilities);
3108 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
3109 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3110 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3112 ComponentInstance currentCompInstance = null;
3114 for (ComponentInstance compInstance : componentInstancesList) {
3116 if (compInstance.getName()
3117 .equals(nodesInfoValue.getName())) {
3118 currentCompInstance = compInstance;
3124 if (currentCompInstance == null) {
3125 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
3126 BeEcompErrorManager.getInstance()
3127 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
3128 resource.getUniqueId(), ErrorSeverity.ERROR);
3129 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3131 String resourceInstanceId = currentCompInstance.getUniqueId();
3133 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
3135 if (regMap != null) {
3136 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
3139 while (nodesRegValue.hasNext()) {
3140 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3142 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3143 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3144 log.debug("Going to create relation {}", uploadRegInfo.getName());
3145 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
3146 String regName = uploadRegInfo.getName();
3147 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3148 regCapRelDef.setFromNode(resourceInstanceId);
3149 log.debug("try to find available requirement {} ", regName);
3150 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3151 yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
3152 if (eitherReqStatus.isRight()) {
3153 log.debug("failed to find available requirement {} status is {}", regName,
3154 eitherReqStatus.right()
3156 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
3157 return eitherReqStatus.right()
3161 RequirementDefinition validReq = eitherReqStatus.left()
3163 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3164 .getRelationships();
3165 if (reqAndRelationshipPairList == null) {
3166 reqAndRelationshipPairList = new ArrayList<>();
3168 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3169 reqAndRelationshipPair.setRequirement(regName);
3170 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3171 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3172 RelationshipImpl relationship = new RelationshipImpl();
3173 relationship.setType(validReq.getCapability());
3174 reqAndRelationshipPair.setRelationships(relationship);
3176 ComponentInstance currentCapCompInstance = null;
3177 for (ComponentInstance compInstance : componentInstancesList) {
3178 if (compInstance.getName()
3179 .equals(uploadRegInfo.getNode())) {
3180 currentCapCompInstance = compInstance;
3185 if (currentCapCompInstance == null) {
3186 log.debug("The component instance with name {} not found on resource {} ",
3187 uploadRegInfo.getNode(), resource.getUniqueId());
3188 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
3189 BeEcompErrorManager.getInstance()
3190 .logInternalDataError(
3191 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
3192 resource.getUniqueId(), ErrorSeverity.ERROR);
3193 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3195 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3196 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3197 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3198 currentCapCompInstance, uploadRegInfo);
3200 if (aviableCapForRel == null) {
3201 log.debug("aviable capability was not found. req name is {} component instance is {}",
3202 validReq.getName(), currentCapCompInstance.getUniqueId());
3203 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());
3204 BeEcompErrorManager.getInstance()
3205 .logInternalDataError(
3206 "aviable capability was not found. req name is " + validReq.getName()
3207 + " component instance is " + currentCapCompInstance.getUniqueId(),
3208 resource.getUniqueId(), ErrorSeverity.ERROR);
3209 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3211 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3212 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3213 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3215 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3216 capReqRel.setRelation(reqAndRelationshipPair);
3217 reqAndRelationshipPairList.add(capReqRel);
3218 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3219 relations.add(regCapRelDef);
3222 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3223 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3225 return componentsUtils.getResponseFormat(ActionStatus.OK);
3228 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
3229 Resource originResource, ComponentInstance currentCompInstance,
3230 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3231 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3232 if (MapUtils.isNotEmpty(propMap)) {
3233 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
3234 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3236 if (CollectionUtils.isEmpty(originResource.getInputs())) {
3237 log.debug("failed to find properties ");
3238 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
3239 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
3241 originResource.getInputs()
3242 .forEach(p -> addInput(currPropertiesMap, p));
3243 for (List<UploadPropInfo> propertyList : propMap.values()) {
3244 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
3247 currPropertiesMap.values()
3248 .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
3249 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3253 private void processProperty(Resource resource, ComponentInstance currentCompInstance,
3254 Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
3255 List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
3256 UploadPropInfo propertyInfo = propertyList.get(0);
3257 String propName = propertyInfo.getName();
3258 if (!currPropertiesMap.containsKey(propName)) {
3259 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3260 StatusCode.ERROR,"ERROR failed to find property: {}",propName);
3261 log.debug("failed to find property {} ", propName);
3262 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
3264 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3265 ComponentInstanceInput property = null;
3267 String value = null;
3268 List<GetInputValueDataDefinition> getInputs = null;
3269 boolean isValidate = true;
3270 if (propertyInfo.getValue() != null) {
3271 getInputs = propertyInfo.getGet_input();
3272 isValidate = getInputs == null || getInputs.isEmpty();
3274 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3276 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3277 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3280 String innerType = null;
3281 property = new ComponentInstanceInput(curPropertyDef, value, null);
3283 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3285 property.setValue(validPropertyVAlue);
3287 if (isNotEmpty(getInputs)) {
3288 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3289 for (GetInputValueDataDefinition getInput : getInputs) {
3290 List<InputDefinition> inputs = resource.getInputs();
3291 if (CollectionUtils.isEmpty(inputs)) {
3292 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3293 StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
3294 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
3295 currentCompInstance.getUniqueId());
3296 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3299 Optional<InputDefinition> optional = inputs.stream()
3300 .filter(p -> p.getName()
3301 .equals(getInput.getInputName()))
3303 if (!optional.isPresent()) {
3304 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3305 StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
3306 log.debug("Failed to find input {} ", getInput.getInputName());
3307 // @@TODO error message
3308 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3310 InputDefinition input = optional.get();
3311 getInput.setInputId(input.getUniqueId());
3312 getInputValues.add(getInput);
3314 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3315 processGetInput(getInputValues, inputs, getInputIndex);
3317 property.setGetInputValues(getInputValues);
3319 instPropList.add(property);
3320 // delete overriden property
3321 currPropertiesMap.remove(property.getName());
3324 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
3325 GetInputValueDataDefinition getInputIndex) {
3326 Optional<InputDefinition> optional;
3327 if (getInputIndex != null) {
3328 optional = inputs.stream()
3329 .filter(p -> p.getName()
3330 .equals(getInputIndex.getInputName()))
3332 if (!optional.isPresent()) {
3333 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3334 // @@TODO error message
3335 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3337 InputDefinition inputIndex = optional.get();
3338 getInputIndex.setInputId(inputIndex.getUniqueId());
3339 getInputValues.add(getInputIndex);
3343 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
3344 String propName = prop.getName();
3345 if (!currPropertiesMap.containsKey(propName)) {
3346 currPropertiesMap.put(propName, prop);
3350 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3351 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
3352 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3354 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3355 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
3357 List<PropertyDefinition> listFromMap = originResource.getProperties();
3358 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3359 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3360 StatusCode.ERROR,"ERROR Failed to find properties");
3361 log.debug("failed to find properties");
3362 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3364 if (listFromMap == null || listFromMap.isEmpty()) {
3365 return componentsUtils.getResponseFormat(ActionStatus.OK);
3367 for (PropertyDefinition prop : listFromMap) {
3368 String propName = prop.getName();
3369 if (!currPropertiesMap.containsKey(propName)) {
3370 currPropertiesMap.put(propName, prop);
3373 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3374 if (propMap != null && propMap.size() > 0) {
3375 for (List<UploadPropInfo> propertyList : propMap.values()) {
3377 UploadPropInfo propertyInfo = propertyList.get(0);
3378 String propName = propertyInfo.getName();
3379 if (!currPropertiesMap.containsKey(propName)) {
3380 log.debug("failed to find property {} ", propName);
3381 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
3382 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3384 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3385 ComponentInstanceProperty property = null;
3387 String value = null;
3388 List<GetInputValueDataDefinition> getInputs = null;
3389 boolean isValidate = true;
3390 if (propertyInfo.getValue() != null) {
3391 getInputs = propertyInfo.getGet_input();
3392 isValidate = getInputs == null || getInputs.isEmpty();
3394 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3396 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3397 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3400 String innerType = null;
3401 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3403 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3404 property.setValue(validatePropValue);
3406 if (getInputs != null && !getInputs.isEmpty()) {
3407 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3408 for (GetInputValueDataDefinition getInput : getInputs) {
3409 List<InputDefinition> inputs = resource.getInputs();
3410 if (inputs == null || inputs.isEmpty()) {
3411 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
3412 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
3413 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
3415 .map(GetInputValueDataDefinition::getInputName)
3419 InputDefinition input = findInputByName(inputs, getInput);
3420 getInput.setInputId(input.getUniqueId());
3421 getInputValues.add(getInput);
3423 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3424 if (getInputIndex != null) {
3425 input = findInputByName(inputs, getInputIndex);
3426 getInputIndex.setInputId(input.getUniqueId());
3427 getInputValues.add(getInputIndex);
3432 property.setGetInputValues(getInputValues);
3434 instPropList.add(property);
3435 // delete overriden property
3436 currPropertiesMap.remove(property.getName());
3439 // add rest of properties
3440 if (!currPropertiesMap.isEmpty()) {
3441 for (PropertyDefinition value : currPropertiesMap.values()) {
3442 instPropList.add(new ComponentInstanceProperty(value));
3445 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3446 return componentsUtils.getResponseFormat(ActionStatus.OK);
3449 // US740820 Relate RIs according to capability name
3450 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3451 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3452 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
3453 .equals(uploadReqInfo.getCapabilityName())) {// get
3457 return findAvailableCapability(validReq, currentCapCompInstance);
3459 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3462 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3463 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3464 CapabilityDefinition cap = null;
3465 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3466 if (!capMap.containsKey(validReq.getCapability())) {
3469 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
3471 .filter(p -> p.getName()
3472 .equals(uploadReqInfo.getCapabilityName()))
3474 if (!capByName.isPresent()) {
3477 cap = capByName.get();
3479 if (isBoundedByOccurrences(cap)) {
3480 String leftOccurrences = cap.getLeftOccurrences();
3481 int left = Integer.parseInt(leftOccurrences);
3484 cap.setLeftOccurrences(String.valueOf(left));
3492 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
3493 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
3494 if (capMap.containsKey(validReq.getCapability())) {
3495 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3497 for (CapabilityDefinition cap : capList) {
3498 if (isBoundedByOccurrences(cap)) {
3499 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
3500 : cap.getMaxOccurrences();
3501 int left = Integer.parseInt(leftOccurrences);
3504 cap.setLeftOccurrences(String.valueOf(left));
3515 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
3516 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
3517 .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
3520 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3521 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3523 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3524 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3525 RequirementDefinition validRegDef = null;
3527 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3528 for (RequirementDefinition reqDef : entry.getValue()) {
3529 if (reqDef.getName()
3531 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3532 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3533 String leftOccurrences = reqDef.getLeftOccurrences();
3534 if (leftOccurrences == null) {
3535 leftOccurrences = reqDef.getMaxOccurrences();
3537 int left = Integer.parseInt(leftOccurrences);
3540 reqDef.setLeftOccurrences(String.valueOf(left));
3541 validRegDef = reqDef;
3547 validRegDef = reqDef;
3553 if (validRegDef != null) {
3558 for (RequirementDefinition reqDef : list) {
3559 if (reqDef.getName()
3561 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3562 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3563 String leftOccurrences = reqDef.getLeftOccurrences();
3564 if (leftOccurrences == null) {
3565 leftOccurrences = reqDef.getMaxOccurrences();
3567 int left = Integer.parseInt(leftOccurrences);
3570 reqDef.setLeftOccurrences(String.valueOf(left));
3571 validRegDef = reqDef;
3577 validRegDef = reqDef;
3583 if (validRegDef == null) {
3584 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3585 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3586 return Either.right(responseFormat);
3588 return Either.left(validRegDef);
3591 private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
3592 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
3594 Either<Resource, ResponseFormat> eitherResource;
3595 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3596 if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3597 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3598 throw new ByResponseFormatComponentException(responseFormat);
3600 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3601 nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
3603 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3604 uploadResInstancesMap.values()
3605 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
3606 existingNodeTypesByResourceNames, resourcesInstancesMap));
3607 if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
3608 Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
3610 .collect(toMap(Resource::getUniqueId, r -> r));
3611 oldResource.getComponentInstances()
3613 .filter(i -> !i.isCreatedFromCsar())
3614 .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
3615 getOriginResource(existingNodeTypesByUids, uiInst)));
3618 if (isNotEmpty(resourcesInstancesMap)) {
3620 toscaOperationFacade.associateComponentInstancesToComponent(resource,
3621 resourcesInstancesMap, false, oldResource != null);
3622 } catch (StorageException exp) {
3623 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
3624 log.debug("Failed to add component instances to container component {}", resource.getName());
3625 ResponseFormat responseFormat = componentsUtils
3626 .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
3627 eitherResource = Either.right(responseFormat);
3628 throw new ByResponseFormatComponentException(eitherResource.right().value());
3632 if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
3633 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3634 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3635 BeEcompErrorManager.getInstance()
3636 .logBeDaoSystemError(
3637 "Error when create resource instance from csar. ComponentInstances list empty");
3638 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3643 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3644 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
3645 Map<ComponentInstance, Resource> resourcesInstancesMap) {
3646 Either<Resource, ResponseFormat> eitherResource;
3647 log.debug("*************Going to create resource instances {}", yamlName);
3648 // updating type if the type is node type name - we need to take the
3650 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3651 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3652 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
3653 .getToscaResourceName());
3655 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3656 existingnodeTypeMap);
3658 ComponentInstance componentInstance = new ComponentInstance();
3659 componentInstance.setComponentUid(refResource.getUniqueId());
3660 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3661 if(directives != null && !directives.isEmpty()) {
3662 componentInstance.setDirectives(new ArrayList<>(directives));
3664 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3665 if (uploadNodeFilterInfo != null){
3666 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3667 componentInstance.getUniqueId()));
3669 ComponentTypeEnum containerComponentType = resource.getComponentType();
3670 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3671 if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3672 && isNotEmpty(refResource.getCapabilities())) {
3673 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3674 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3675 refResource.getUniqueId(), refResource.getCapabilities(),
3676 uploadComponentInstanceInfo.getCapabilities());
3677 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3680 if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
3681 Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
3682 Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
3683 Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
3684 .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
3685 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
3686 Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
3687 for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
3688 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
3689 to.setFile(entry.getValue().getFile());
3690 to.setType(entry.getValue().getType());
3691 toscaArtifacts.put(entry.getKey(), to);
3693 componentInstance.setToscaArtifacts(toscaArtifacts);
3696 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3697 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
3698 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3699 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3700 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3702 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3703 componentInstance.setName(uploadComponentInstanceInfo.getName());
3704 componentInstance.setIcon(origResource.getIcon());
3705 componentInstance.setCreatedFrom(CreatedFrom.CSAR);
3706 resourcesInstancesMap.put(componentInstance, origResource);
3709 private ComponentParametersView getComponentWithInstancesFilter() {
3710 ComponentParametersView parametersView = new ComponentParametersView();
3711 parametersView.disableAll();
3712 parametersView.setIgnoreComponentInstances(false);
3713 parametersView.setIgnoreInputs(false);
3714 // inputs are read when creating
3715 // property values on instances
3716 parametersView.setIgnoreUsers(false);
3717 return parametersView;
3720 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3721 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3722 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3723 if (originCapabilities.containsKey(currEntry.getKey())) {
3724 currEntry.getValue()
3726 .forEach(cap -> cap.setType(currEntry.getKey()));
3729 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3730 capabilities.getValue()
3733 if (uploadedCapabilities.containsKey(cap.getName())) {
3734 uploadedCapabilities.get(cap.getName())
3737 c.setName(cap.getName());
3738 c.setType(cap.getType());
3745 private Resource validateResourceInstanceBeforeCreate(String yamlName,
3746 UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
3749 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
3750 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3751 Resource refResource;
3752 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3753 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3755 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3756 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3757 if (findResourceEither.isRight()) {
3759 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type {}",
3760 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3761 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3763 refResource = findResourceEither.left().value();
3764 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3766 String componentState = refResource.getComponentMetadataDefinition()
3767 .getMetadataDataDefinition()
3769 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3771 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3772 refResource.getName(), componentState);
3773 throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
3774 refResource.getComponentType().getValue(),refResource.getName(), componentState);
3777 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3778 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3779 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3780 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3785 public Resource propagateStateToCertified(User user, Resource resource,
3786 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3787 boolean forceCertificationAllowed) {
3789 boolean failed = false;
3791 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3792 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3793 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3795 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3796 Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
3797 resource, user, false, inTransaction, needLock, false);
3800 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3801 } catch (ComponentException e) {
3803 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3807 BeEcompErrorManager.getInstance()
3808 .logBeSystemError("Change LifecycleState - Certify");
3809 if (!inTransaction) {
3810 janusGraphDao.rollback();
3812 } else if (!inTransaction) {
3813 janusGraphDao.commit();
3818 private Resource nodeFullCertification(String uniqueId, User user,
3819 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3820 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
3821 inTransaction, needLock);
3822 if(resourceResponse.isRight()){
3823 throw new ByResponseFormatComponentException(resourceResponse.right().value());
3825 return resourceResponse.left().value();
3828 private Resource nodeForceCertification(Resource resource, User user,
3829 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3830 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3834 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
3836 final boolean isNormative,
3837 final boolean isInTransaction,
3838 final boolean needLock,
3839 final CsarInfo csarInfo,
3840 final String nodeName,
3841 final boolean isNested) {
3843 ImmutablePair<Resource, ActionStatus> result = null;
3844 // check if resource already exists (search by tosca name = type)
3845 final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3846 final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3847 .getLatestByToscaResourceName(resource.getToscaResourceName());
3849 if (latestByToscaName.isLeft()) {
3850 Resource foundResource = latestByToscaName.left().value();
3851 // we don't allow updating names of top level types
3852 if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
3853 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3854 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3855 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3856 foundResource.getName(), resource.getToscaResourceName());
3857 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3858 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3859 throwComponentException(responseFormat);
3861 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3862 } else if (isNotFound(latestByToscaName)) {
3863 if (isNestedResource) {
3864 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
3865 isNested, nodeName);
3867 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3870 StorageOperationStatus status = latestByToscaName.right().value();
3871 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3872 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
3873 .convertFromStorageResponse(latestByToscaName.right().value()), resource);
3874 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3875 throwComponentException(responseFormat);
3880 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3881 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3884 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
3886 final boolean isNormative,
3887 final boolean isInTransaction,
3888 final boolean needLock,
3889 final CsarInfo csarInfo,
3890 final boolean isNested,
3891 final String nodeName) {
3892 final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3893 .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
3894 .name(), csarInfo.getVfResourceName(), nodeName).getRight());
3895 if (latestByToscaName.isLeft()) {
3896 final Resource nestedResource = (Resource) latestByToscaName.left().value();
3897 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3898 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
3899 resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3900 if (eitherValidation.isRight()) {
3901 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3903 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3905 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3909 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3910 return getResourceEither.isRight() && getResourceEither.right()
3911 .value() == StorageOperationStatus.NOT_FOUND;
3914 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
3915 boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3916 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3917 validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3918 final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
3920 Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
3921 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
3922 ASDCKpiApi.countImportResourcesKPI();
3923 return resourcePair;
3926 public boolean isResourceExist(String resourceName) {
3927 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3928 return latestByName.isLeft();
3931 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
3932 Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
3933 String lockedResourceId = oldResource.getUniqueId();
3934 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3935 oldResource.getVersion(), oldResource.getLifecycleState());
3936 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3938 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3939 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3940 mergeOldResourceMetadataWithNew(oldResource, newResource);
3942 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3943 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource,
3944 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3945 // contact info normalization
3946 newResource.setContactId(newResource.getContactId()
3948 PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
3949 // non-updatable fields
3950 newResource.setCreatorUserId(user.getUserId());
3951 newResource.setCreatorFullName(user.getFullName());
3952 newResource.setLastUpdaterUserId(user.getUserId());
3953 newResource.setLastUpdaterFullName(user.getFullName());
3954 newResource.setUniqueId(oldResource.getUniqueId());
3955 newResource.setVersion(oldResource.getVersion());
3956 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3957 newResource.setLifecycleState(oldResource.getLifecycleState());
3958 newResource.setUUID(oldResource.getUUID());
3959 newResource.setNormalizedName(oldResource.getNormalizedName());
3960 newResource.setSystemName(oldResource.getSystemName());
3961 if (oldResource.getCsarUUID() != null) {
3962 newResource.setCsarUUID(oldResource.getCsarUUID());
3964 if (oldResource.getImportedToscaChecksum() != null) {
3965 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3967 newResource.setAbstract(oldResource.isAbstract());
3969 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom()
3971 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3973 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType()
3975 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3977 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion()
3979 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3982 // created without tosca artifacts - add the placeholders
3983 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts()
3985 setToscaArtifactsPlaceHolders(newResource, user);
3988 if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3989 newResource.setInterfaces(oldResource.getInterfaces());
3992 if (CollectionUtils.isEmpty(newResource.getProperties())) {
3993 newResource.setProperties(oldResource.getProperties());
3996 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3997 .overrideComponent(newResource, oldResource);
3999 if (overrideResource.isRight()) {
4000 ResponseFormat responseFormat = componentsUtils
4001 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
4002 .value()), newResource);
4003 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
4005 throwComponentException(responseFormat);
4007 updateCatalog(overrideResource.left()
4008 .value(), ChangeTypeEnum.LIFECYCLE);
4010 log.debug("Resource updated successfully!!!");
4011 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4012 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4013 ResourceVersionInfo.newBuilder()
4014 .state(oldResource.getLifecycleState()
4016 .version(oldResource.getVersion())
4019 resourcePair = new ImmutablePair<>(overrideResource.left()
4020 .value(), ActionStatus.OK);
4021 return resourcePair;
4023 if (resourcePair == null) {
4024 BeEcompErrorManager.getInstance()
4025 .logBeSystemError("Change LifecycleState - Certify");
4026 janusGraphDao.rollback();
4027 } else if (!inTransaction) {
4028 janusGraphDao.commit();
4031 log.debug("unlock resource {}", lockedResourceId);
4032 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4039 * Merge old resource with new. Keep old category and vendor name without
4042 * @param oldResource
4043 * @param newResource
4045 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4047 // keep old category and vendor name without change
4048 // merge the rest of the resource metadata
4049 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4050 newResource.setTags(oldResource.getTags());
4053 if (newResource.getDescription() == null) {
4054 newResource.setDescription(oldResource.getDescription());
4057 if (newResource.getVendorRelease() == null) {
4058 newResource.setVendorRelease(oldResource.getVendorRelease());
4061 if (newResource.getResourceVendorModelNumber() == null) {
4062 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4065 if (newResource.getContactId() == null) {
4066 newResource.setContactId(oldResource.getContactId());
4069 newResource.setCategories(oldResource.getCategories());
4070 if (newResource.getVendorName() == null) {
4071 newResource.setVendorName(oldResource.getVendorName());
4073 List<GroupDefinition>oldForUpdate = oldResource.getGroups();
4074 if(CollectionUtils.isNotEmpty(oldForUpdate)){
4075 List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
4077 groupForUpdate.stream().filter(group -> group.isVspOriginated())
4078 .forEach(group -> group.setName(group.getInvariantName()));
4080 newResource.setGroups(groupForUpdate);
4084 if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
4085 ResourceTypeEnum updatedResourceType = newResource.getResourceType();
4086 Component derivedFromResource = getParentComponent(newResource);
4087 if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
4088 Resource parentResource = (Resource) derivedFromResource;
4089 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
4090 parentResource.getResourceType() != updatedResourceType) {
4091 BeEcompErrorManager.getInstance()
4092 .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
4093 ErrorSeverity.ERROR);
4094 log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
4095 newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
4096 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
4103 private Component getParentComponent(Resource newResource) {
4104 String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
4105 Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
4106 if(latestByToscaResourceName.isRight()){
4107 BeEcompErrorManager.getInstance()
4108 .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
4109 log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
4110 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
4112 return latestByToscaResourceName.left().value();
4115 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
4116 boolean inTransaction, boolean needLock) {
4118 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
4120 return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4121 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
4123 .on(response -> failOnChangeState(response, user, oldResource, newResource));
4128 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
4129 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
4130 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4131 ResourceVersionInfo.newBuilder()
4132 .state(oldResource.getLifecycleState()
4134 .version(oldResource.getVersion())
4136 throw new ByResponseFormatComponentException(response);
4139 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
4140 boolean inTransaction, CsarInfo csarInfo) {
4142 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4143 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4144 validateLifecycleTypesCreate(user, resource, actionEnum);
4145 validateResourceType(user, resource, actionEnum);
4146 resource.setCreatorUserId(user.getUserId());
4147 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4148 resource.setContactId(resource.getContactId()
4150 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4151 String resourceSystemName;
4152 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4153 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4155 resourceSystemName = resource.getSystemName();
4157 resource.setToscaResourceName(CommonBeUtils
4158 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4161 // Generate invariant UUID - must be here and not in operation since it
4162 // should stay constant during clone
4164 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4165 resource.setInvariantUUID(invariantUUID);
4170 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4171 AuditingActionEnum actionEnum) {
4172 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4173 if (resource.getResourceType() == null) {
4174 log.debug("Invalid resource type for resource");
4175 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4176 eitherResult = Either.right(errorResponse);
4177 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4179 return eitherResult;
4182 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4183 AuditingActionEnum actionEnum) {
4184 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4185 if (resource.getInterfaces() != null && resource.getInterfaces()
4187 log.debug("validate interface lifecycle Types Exist");
4188 Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
4191 while (intItr.hasNext() && eitherResult.isLeft()) {
4192 InterfaceDefinition interfaceDefinition = intItr.next();
4193 String intType = interfaceDefinition.getUniqueId();
4194 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4195 .getInterface(intType);
4196 if (eitherCapTypeFound.isRight()) {
4197 if (eitherCapTypeFound.right()
4198 .value() == StorageOperationStatus.NOT_FOUND) {
4199 BeEcompErrorManager.getInstance()
4200 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
4201 "Interface", intType);
4202 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4203 intType, resource.getName());
4204 BeEcompErrorManager.getInstance()
4205 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4206 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
4211 ResponseFormat errorResponse = componentsUtils
4212 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4213 eitherResult = Either.right(errorResponse);
4214 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4219 return eitherResult;
4222 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4223 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4224 boolean inTransaction) {
4226 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4227 if (resource.getCapabilities() != null && resource.getCapabilities()
4229 log.debug("validate capability Types Exist - capabilities section");
4231 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
4234 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4235 eitherResult, typeEntry, inTransaction);
4236 if (eitherResult.isRight()) {
4237 return Either.right(eitherResult.right()
4243 if (resource.getRequirements() != null && resource.getRequirements()
4245 log.debug("validate capability Types Exist - requirements section");
4246 for (String type : resource.getRequirements()
4248 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4249 resource.getRequirements()
4251 actionEnum, eitherResult, type, inTransaction);
4252 if (eitherResult.isRight()) {
4253 return Either.right(eitherResult.right()
4259 return eitherResult;
4262 // @param typeObject- the object to which the validation is done
4263 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4264 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4265 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4266 boolean inTransaction) {
4267 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4268 .getCapabilityType(type, inTransaction);
4269 if (eitherCapTypeFound.isRight()) {
4270 if (eitherCapTypeFound.right()
4271 .value() == StorageOperationStatus.NOT_FOUND) {
4272 BeEcompErrorManager.getInstance()
4273 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4275 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4276 resource.getName());
4277 BeEcompErrorManager.getInstance()
4278 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4280 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
4283 ResponseFormat errorResponse = null;
4285 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4287 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4290 eitherResult = Either.right(errorResponse);
4291 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4293 return eitherResult;
4296 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4297 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4298 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4299 boolean inTransaction) {
4300 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4301 .getCapabilityType(typeEntry.getKey(), inTransaction);
4302 if (eitherCapTypeFound.isRight()) {
4303 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4304 BeEcompErrorManager.getInstance()
4305 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4306 typeEntry.getKey());
4307 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4308 typeEntry.getKey(), resource.getName());
4309 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4311 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4312 eitherCapTypeFound.right().value().name());
4313 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4314 typeEntry.getKey());
4315 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4316 return Either.right(errorResponse);
4318 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4319 if (capabilityTypeDefinition.getProperties() != null) {
4320 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4321 List<ComponentInstanceProperty> properties = capDef.getProperties();
4322 List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
4323 if (properties == null || properties.isEmpty()) {
4324 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4325 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4326 changedProperties.add(newProp);
4329 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4330 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4331 PropertyDefinition propFromDef = prop.getValue();
4332 boolean propFound = false;
4333 for (ComponentInstanceProperty cip : properties) {
4334 if (propFromDef.getName().equals(cip.getName())) {
4335 //merge property value and property description only, ignore other fields
4336 if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
4337 propFromDef.setDescription(cip.getDescription());
4339 propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
4340 if(cip.getValue() != null){
4341 propFromDef.setValue(cip.getValue());
4343 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4345 properties.remove(cip);
4350 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4353 if (!propsToAdd.isEmpty()) {
4354 changedProperties.addAll(propsToAdd);
4357 capDef.setProperties(changedProperties);
4360 return eitherResult;
4363 public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
4364 boolean isNormative, boolean inTransaction) {
4367 // lock new resource name in order to avoid creation resource with same
4369 Resource createdResource = null;
4370 if (!inTransaction) {
4371 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4373 if (lockResult.isRight()) {
4374 ResponseFormat responseFormat = lockResult.right().value();
4375 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4376 throw new ByResponseFormatComponentException(responseFormat);
4379 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4382 if (resource.deriveFromGeneric()) {
4383 handleResourceGenericType(resource);
4385 createdResource = createResourceTransaction(resource, user, isNormative);
4386 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4387 createdResource, actionEnum);
4388 ASDCKpiApi.countCreatedResourcesKPI();
4389 } catch (ComponentException e) {
4390 ResponseFormat responseFormat = e.getResponseFormat() == null
4391 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
4392 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4394 } catch (StorageException e) {
4395 ResponseFormat responseFormat = componentsUtils
4396 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
4397 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4400 if (!inTransaction) {
4401 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4402 NodeTypeEnum.Resource);
4405 return createdResource;
4408 private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
4409 // validate resource name uniqueness
4410 log.debug("validate resource name");
4411 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4412 resource.getName(), resource.getResourceType(), resource.getComponentType());
4413 if (eitherValidation.isRight()) {
4414 loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
4415 StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
4416 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4417 eitherValidation.right()
4419 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
4422 if (eitherValidation.left()
4424 log.debug("resource with name: {}, already exists", resource.getName());
4425 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
4426 StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
4427 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4428 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4431 log.debug("send resource {} to dao for create", resource.getName());
4433 createArtifactsPlaceHolderData(resource, user);
4436 log.debug("enrich resource with creator, version and state");
4437 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4438 resource.setVersion(INITIAL_VERSION);
4439 resource.setHighestVersion(true);
4440 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4441 resource.setAbstract(false);
4444 return toscaOperationFacade.createToscaComponent(resource)
4446 .on(r -> throwComponentExceptionByResource(r, resource));
4449 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
4450 ResponseFormat responseFormat = componentsUtils
4451 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
4452 throw new ByResponseFormatComponentException(responseFormat);
4455 private void createArtifactsPlaceHolderData(Resource resource, User user) {
4456 // create mandatory artifacts
4458 // TODO it must be removed after that artifact uniqueId creation will be
4459 // moved to ArtifactOperation
4461 setInformationalArtifactsPlaceHolder(resource, user);
4462 setDeploymentArtifactsPlaceHolder(resource, user);
4463 setToscaArtifactsPlaceHolders(resource, user);
4466 @SuppressWarnings("unchecked")
4468 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4469 Resource resource = (Resource) component;
4470 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4471 if (artifactMap == null) {
4472 artifactMap = new HashMap<>();
4474 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4476 .getDeploymentResourceArtifacts();
4477 if (deploymentResourceArtifacts != null) {
4478 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
4479 deploymentResourceArtifacts
4480 .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
4482 resource.setDeploymentArtifacts(artifactMap);
4485 private void processDeploymentResourceArtifacts(User user, Resource resource,
4486 Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
4487 boolean shouldCreateArtifact = true;
4488 Map<String, Object> artifactDetails = (Map<String, Object>) v;
4489 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4490 if (object != null) {
4491 List<String> artifactTypes = (List<String>) object;
4492 if (!artifactTypes.contains(resource.getResourceType()
4494 shouldCreateArtifact = false;
4498 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
4500 if (shouldCreateArtifact) {
4501 if (artifactsBusinessLogic != null) {
4502 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4503 resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
4504 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
4505 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4511 @SuppressWarnings("unchecked")
4512 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4513 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4514 if (artifactMap == null) {
4515 artifactMap = new HashMap<>();
4517 String resourceUniqueId = resource.getUniqueId();
4518 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
4520 .getExcludeResourceCategory();
4521 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
4523 .getExcludeResourceType();
4524 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4526 .getInformationalResourceArtifacts();
4527 List<CategoryDefinition> categories = resource.getCategories();
4528 boolean isCreateArtifact = true;
4529 if (exludeResourceCategory != null) {
4530 String category = categories.get(0)
4532 isCreateArtifact = exludeResourceCategory.stream()
4533 .noneMatch(e -> e.equalsIgnoreCase(category));
4535 if (isCreateArtifact && exludeResourceType != null) {
4536 String resourceType = resource.getResourceType()
4538 isCreateArtifact = exludeResourceType.stream()
4539 .noneMatch(e -> e.equalsIgnoreCase(resourceType));
4541 if (informationalResourceArtifacts != null && isCreateArtifact) {
4542 Set<String> keys = informationalResourceArtifacts.keySet();
4543 for (String informationalResourceArtifactName : keys) {
4544 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4545 .get(informationalResourceArtifactName);
4546 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4547 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4548 ArtifactGroupTypeEnum.INFORMATIONAL);
4549 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4553 resource.setArtifacts(artifactMap);
4563 public ResponseFormat deleteResource(String resourceId, User user) {
4564 ResponseFormat responseFormat;
4565 validateUserExists(user);
4567 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4568 if (resourceStatus.isRight()) {
4569 log.debug("failed to get resource {}", resourceId);
4570 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4574 Resource resource = resourceStatus.left()
4577 StorageOperationStatus result = StorageOperationStatus.OK;
4578 lockComponent(resourceId, resource, "Mark resource to delete");
4581 result = markComponentToDelete(resource);
4582 if (result == StorageOperationStatus.OK) {
4583 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4585 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4586 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4588 return responseFormat;
4591 if (result == null || result != StorageOperationStatus.OK) {
4592 janusGraphDao.rollback();
4594 janusGraphDao.commit();
4596 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
4601 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
4602 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4603 validateUserExists(user);
4604 Resource resource = null;
4605 StorageOperationStatus result = StorageOperationStatus.OK;
4606 boolean failed = false;
4609 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
4610 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
4611 if (resourceStatus.isRight()) {
4612 log.debug("failed to get resource {} version {}", resourceName, version);
4613 return componentsUtils
4614 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4615 .value()), resourceName);
4618 resource = resourceStatus.left()
4622 janusGraphDao.commit();
4624 if (resource != null) {
4625 lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
4627 result = markComponentToDelete(resource);
4628 if (result != StorageOperationStatus.OK) {
4629 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4630 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4631 return responseFormat;
4633 }catch (ComponentException e){
4637 if (failed || result == null || result != StorageOperationStatus.OK) {
4638 janusGraphDao.rollback();
4640 janusGraphDao.commit();
4642 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
4645 return responseFormat;
4648 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
4651 validateUserExists(user);
4654 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
4655 if (storageStatus.isRight()) {
4656 log.debug("failed to get resource by id {}", resourceId);
4657 return Either.right(componentsUtils
4658 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
4659 .value()), resourceId));
4661 if (!(storageStatus.left()
4662 .value() instanceof Resource)) {
4663 return Either.right(componentsUtils.getResponseFormatByResource(
4664 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4666 return Either.left(storageStatus.left()
4671 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4674 validateUserExists(userId);
4676 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4677 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4678 if (getResource.isRight()) {
4679 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4680 return Either.right(componentsUtils
4681 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
4682 .value()), resourceName));
4684 return Either.left(getResource.left()
4689 * updateResourceMetadata
4692 * - modifier data (userId)
4693 * @param inTransaction
4695 * @param resourceIdToUpdate
4696 * - the resource identifier
4697 * @param newResource
4698 * @return Either<Resource , responseFormat>
4700 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
4701 User user, boolean inTransaction) {
4703 validateUserExists(user.getUserId());
4705 log.debug("Get resource with id {}", resourceIdToUpdate);
4706 boolean needToUnlock = false;
4709 if (currentResource == null) {
4710 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4711 .getToscaElement(resourceIdToUpdate);
4712 if (storageStatus.isRight()) {
4713 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4714 componentsUtils.convertFromStorageResponse(storageStatus.right()
4719 currentResource = storageStatus.left()
4722 // verify that resource is checked-out and the user is the last
4724 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4725 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4729 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4730 NodeTypeEnum.Resource);
4731 if (lockResult != StorageOperationStatus.OK) {
4732 BeEcompErrorManager.getInstance()
4733 .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
4734 resourceIdToUpdate);
4735 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4736 ResponseFormat responseFormat = componentsUtils
4737 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4738 throw new ByResponseFormatComponentException(responseFormat);
4741 needToUnlock = true;
4743 // critical section starts here
4744 // convert json to object
4746 // Update and updated resource must have a non-empty "derivedFrom"
4748 // This code is not called from import resources, because of root
4749 // VF "derivedFrom" should be null (or ignored)
4750 if (ModelConverter.isAtomicComponent(currentResource)) {
4751 validateDerivedFromNotEmpty(null, newResource, null);
4752 validateDerivedFromNotEmpty(null, currentResource, null);
4754 newResource.setDerivedFrom(null);
4757 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4758 user, currentResource, false, true);
4759 if (dataModelResponse.isRight()) {
4760 log.debug("failed to update resource metadata!!!");
4761 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4764 log.debug("Resource metadata updated successfully!!!");
4765 return dataModelResponse.left()
4768 } catch (ComponentException | StorageException e) {
4769 rollback(inTransaction, newResource, null, null);
4772 if (!inTransaction) {
4773 janusGraphDao.commit();
4776 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4781 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4782 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4783 updateVfModuleGroupsNames(currentResource, newResource);
4784 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4785 // Setting last updater and uniqueId
4786 newResource.setContactId(newResource.getContactId()
4788 newResource.setLastUpdaterUserId(user.getUserId());
4789 newResource.setUniqueId(resourceIdToUpdate);
4790 // Cannot set highest version through UI
4791 newResource.setHighestVersion(currentResource.isHighestVersion());
4792 newResource.setCreationDate(currentResource.getCreationDate());
4794 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4795 newResource, user.getUserId(), inTransaction);
4797 if (processUpdateOfDerivedFrom.isRight()) {
4798 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4799 return Either.right(processUpdateOfDerivedFrom.right()
4803 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4804 if (isNotEmpty(newResource.getGroups())) {
4805 for (GroupDefinition group : newResource.getGroups()) {
4806 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
4807 groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
4808 .getMetadataDataDefinition()
4809 .getUniqueId(), user, newResource.getComponentType(), group, true, false);
4813 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4814 .updateToscaElement(newResource);
4816 if (dataModelResponse.isRight()) {
4817 ResponseFormat responseFormat = componentsUtils
4818 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
4819 .value()), newResource);
4820 return Either.right(responseFormat);
4821 } else if (dataModelResponse.left()
4823 log.debug("No response from updateResource");
4824 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4826 return Either.left(dataModelResponse.left()
4830 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4831 if (currentResource.getGroups() != null && !currentResource.getName()
4832 .equals(newResource.getName())) {
4833 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4835 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4837 newResource.setGroups(updatedGroups);
4841 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4842 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4843 if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
4844 .equals(DEFAULT_GROUP_VF_MODULE)) {
4845 String prefix = updatedGroup.getName()
4846 .substring(0, replacePattern.length());
4847 String newGroupName = updatedGroup.getName()
4848 .replaceFirst(prefix, with);
4849 updatedGroup.setName(newGroupName);
4851 return updatedGroup;
4855 * validateResourceFieldsBeforeCreate
4858 * - modifier data (userId)
4860 private void validateResourceFieldsBeforeCreate(User user, Resource resource,
4861 AuditingActionEnum actionEnum, boolean inTransaction) {
4862 componentValidator.validate(user, resource, actionEnum);
4863 // validate category
4864 log.debug("validate category");
4865 validateCategory(user, resource, actionEnum, inTransaction);
4866 // validate vendor name & release & model number
4867 log.debug("validate vendor name");
4868 validateVendorName(user, resource, actionEnum);
4869 log.debug("validate vendor release");
4870 validateVendorReleaseName(user, resource, actionEnum);
4871 log.debug("validate resource vendor model number");
4872 validateResourceVendorModelNumber(user, resource, actionEnum);
4874 log.debug("validate cost");
4875 validateCost(resource);
4876 // validate licenseType
4877 log.debug("validate licenseType");
4878 validateLicenseType(user, resource, actionEnum);
4879 // validate template (derived from)
4880 log.debug("validate derived from");
4881 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4882 resource.setDerivedFrom(null);
4884 validateDerivedFromExist(user, resource, actionEnum);
4885 // warn about non-updatable fields
4886 checkComponentFieldsForOverrideAttempt(resource);
4887 String currentCreatorFullName = resource.getCreatorFullName();
4888 if (currentCreatorFullName != null) {
4889 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4892 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4893 if (currentLastUpdaterFullName != null) {
4894 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4897 Long currentLastUpdateDate = resource.getLastUpdateDate();
4898 if (currentLastUpdateDate != null) {
4899 log.debug("Resource last update date is automatically set and cannot be updated");
4902 Boolean currentAbstract = resource.isAbstract();
4903 if (currentAbstract != null) {
4904 log.debug("Resource abstract is automatically set and cannot be updated");
4909 * validateResourceFieldsBeforeUpdate
4911 * @param currentResource
4912 * - Resource object to validate
4915 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4916 boolean inTransaction, boolean isNested) {
4917 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4918 warnNonEditableFields(currentResource, updateInfoResource);
4921 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4922 String currentResourceVersion = currentResource.getVersion();
4923 String updatedResourceVersion = updateInfoResource.getVersion();
4925 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4926 log.debug("Resource version is automatically set and cannot be updated");
4929 String currentCreatorUserId = currentResource.getCreatorUserId();
4930 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4932 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4933 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4936 String currentCreatorFullName = currentResource.getCreatorFullName();
4937 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4939 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4940 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4943 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4944 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4946 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4947 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4950 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4951 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4953 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4954 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4956 Long currentCreationDate = currentResource.getCreationDate();
4957 Long updatedCreationDate = updateInfoResource.getCreationDate();
4959 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4960 log.debug("Resource Creation date is automatically set and cannot be updated");
4963 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4964 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4966 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4967 log.debug("Resource last update date is automatically set and cannot be updated");
4970 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4971 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4973 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4974 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4977 Boolean currentAbstract = currentResource.isAbstract();
4978 Boolean updatedAbstract = updateInfoResource.isAbstract();
4980 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4981 log.debug("Resource abstract is automatically set and cannot be updated");
4984 Boolean currentHighestVersion = currentResource.isHighestVersion();
4985 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4987 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4988 log.debug("Resource highest version is automatically set and cannot be updated");
4991 String currentUuid = currentResource.getUUID();
4992 String updatedUuid = updateInfoResource.getUUID();
4994 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4995 log.debug("Resource UUID is automatically set and cannot be updated");
4998 log.debug("Resource Type cannot be updated");
4999 String currentInvariantUuid = currentResource.getInvariantUUID();
5000 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
5002 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5003 log.debug("Resource invariant UUID is automatically set and cannot be updated");
5004 updateInfoResource.setInvariantUUID(currentInvariantUuid);
5008 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
5010 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5011 log.debug("validate resource name before update");
5012 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
5013 log.debug("validate description before update");
5014 componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
5015 log.debug("validate icon before update");
5016 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5017 log.debug("validate tags before update");
5018 componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
5019 log.debug("validate vendor name before update");
5020 validateVendorName(null, updateInfoResource, null);
5021 log.debug("validate resource vendor model number before update");
5022 validateResourceVendorModelNumber(currentResource, updateInfoResource);
5023 log.debug("validate vendor release before update");
5024 validateVendorReleaseName(null, updateInfoResource, null);
5025 log.debug("validate contact info before update");
5026 componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
5027 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
5028 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5029 log.debug("validate category before update");
5030 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5033 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5034 String resourceNameUpdated = updateInfoResource.getName();
5035 String resourceNameCurrent = currentResource.getName();
5036 if (resourceNameCurrent.equals(resourceNameUpdated)) {
5039 // In case of CVFC type we should support the case of old VF with CVFC
5040 // instances that were created without the "Cvfc" suffix
5041 return currentResource.getResourceType() == ResourceTypeEnum.CVFC
5042 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5045 private String addCvfcSuffixToResourceName(String resourceName) {
5046 return resourceName + "Cvfc";
5049 private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
5051 String resourceNameUpdated = updateInfoResource.getName();
5052 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5053 if (isNested || !hasBeenCertified) {
5054 componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
5055 validateResourceNameUniqueness(updateInfoResource);
5056 currentResource.setName(resourceNameUpdated);
5057 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5058 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5061 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5062 resourceNameUpdated);
5063 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5068 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5069 String iconUpdated = updateInfoResource.getIcon();
5070 String iconCurrent = currentResource.getIcon();
5071 if (!iconCurrent.equals(iconUpdated)) {
5072 if (!hasBeenCertified) {
5073 componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
5075 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5076 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5081 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
5082 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5083 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5084 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5085 validateResourceVendorModelNumber(null, updateInfoResource, null);
5089 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5090 boolean hasBeenCertified, boolean inTransaction) {
5091 validateCategory(null, updateInfoResource, null, inTransaction);
5092 if (hasBeenCertified) {
5093 CategoryDefinition currentCategory = currentResource.getCategories()
5095 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
5097 CategoryDefinition updateCategory = updateInfoResource.getCategories()
5099 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
5101 if (!currentCategory.getName()
5102 .equals(updateCategory.getName())
5103 || !currentSubCategory.getName()
5104 .equals(updtaeSubCategory.getName())) {
5105 log.info("Category {} cannot be updated once the resource has been certified once.",
5106 currentResource.getCategories());
5107 ResponseFormat errorResponse = componentsUtils
5108 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5109 return Either.right(errorResponse);
5112 return Either.left(true);
5115 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5116 Resource updateInfoResource, boolean hasBeenCertified) {
5118 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5119 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5120 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5121 || updatedDerivedFrom.isEmpty()) {
5122 log.trace("Update normative types");
5123 return Either.left(true);
5126 String derivedFromCurrent = currentDerivedFrom.get(0);
5127 String derivedFromUpdated = updatedDerivedFrom.get(0);
5129 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5130 if (!hasBeenCertified) {
5131 validateDerivedFromExist(null, updateInfoResource, null);
5133 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5134 currentResource, updateInfoResource, null);
5136 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5138 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5139 return validateDerivedFromExtending;
5143 // For derived from, we must know whether it was actually changed,
5144 // otherwise we must do no action.
5145 // Due to changes it inflicts on data model (remove artifacts,
5146 // properties...), it's not like a flat field which can be
5147 // overwritten if not changed.
5148 // So we must indicate that derived from is not changed
5149 updateInfoResource.setDerivedFrom(null);
5151 return Either.left(true);
5154 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5155 Resource updateInfoResource, boolean hasBeenCertified) {
5157 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5158 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5159 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5160 || updatedDerivedFrom.isEmpty()) {
5161 log.trace("Update normative types");
5162 return Either.left(true);
5165 String derivedFromCurrent = currentDerivedFrom.get(0);
5166 String derivedFromUpdated = updatedDerivedFrom.get(0);
5168 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5169 if (!hasBeenCertified) {
5170 validateDerivedFromExist(null, updateInfoResource, null);
5172 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5173 currentResource, updateInfoResource, null);
5175 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5177 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5178 return validateDerivedFromExtending;
5182 return Either.left(true);
5185 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5186 if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
5190 String templateName = resource.getDerivedFrom()
5192 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5193 .validateToscaResourceNameExists(templateName);
5194 if (dataModelResponse.isRight()) {
5195 StorageOperationStatus storageStatus = dataModelResponse.right()
5197 BeEcompErrorManager.getInstance()
5198 .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5199 log.debug("request to data model failed with error: {}", storageStatus);
5200 ResponseFormat responseFormat = componentsUtils
5201 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5202 log.trace("audit before sending response");
5203 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5204 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
5205 } else if (!dataModelResponse.left()
5207 log.info("resource template with name: {}, does not exists", templateName);
5208 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5209 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5210 throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5214 // Tal G for extending inheritance US815447
5215 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5216 Resource updateInfoResource, AuditingActionEnum actionEnum) {
5217 String currentTemplateName = currentResource.getDerivedFrom()
5219 String updatedTemplateName = updateInfoResource.getDerivedFrom()
5222 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5223 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5224 if (dataModelResponse.isRight()) {
5225 StorageOperationStatus storageStatus = dataModelResponse.right()
5227 BeEcompErrorManager.getInstance()
5228 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5229 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5230 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5231 log.trace("audit before sending response");
5232 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5233 return Either.right(responseFormat);
5236 if (!dataModelResponse.left()
5238 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5239 currentTemplateName);
5240 ResponseFormat responseFormat = componentsUtils
5241 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5242 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5244 return Either.right(responseFormat);
5247 return Either.left(true);
5250 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5251 log.debug("validate resource derivedFrom field");
5252 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
5254 || (resource.getDerivedFrom()
5256 || (resource.getDerivedFrom()
5260 log.info("derived from (template) field is missing for the resource");
5261 ResponseFormat responseFormat = componentsUtils
5262 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5263 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5265 throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5269 private void validateResourceNameUniqueness(Resource resource) {
5271 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5272 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5273 resource.getComponentType());
5274 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
5276 log.debug("resource with name: {}, already exists", resource.getName());
5277 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
5278 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5279 } else if (resourceOperationResponse.isRight()) {
5280 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5281 throw new StorageException(resourceOperationResponse.right()
5286 private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5288 List<CategoryDefinition> categories = resource.getCategories();
5289 if (CollectionUtils.isEmpty(categories)) {
5290 log.debug(CATEGORY_IS_EMPTY);
5291 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5292 ComponentTypeEnum.RESOURCE.getValue());
5293 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5294 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5295 ComponentTypeEnum.RESOURCE.getValue());
5297 if (categories.size() > 1) {
5298 log.debug("Must be only one category for resource");
5299 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
5300 ComponentTypeEnum.RESOURCE.getValue());
5302 CategoryDefinition category = categories.get(0);
5303 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5304 if (CollectionUtils.isEmpty(subcategories)) {
5305 log.debug("Missinig subcategory for resource");
5306 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5308 if (subcategories.size() > 1) {
5309 log.debug("Must be only one sub category for resource");
5310 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5313 SubCategoryDefinition subcategory = subcategories.get(0);
5315 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5316 log.debug(CATEGORY_IS_EMPTY);
5317 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5318 ComponentTypeEnum.RESOURCE.getValue());
5319 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5320 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5321 ComponentTypeEnum.RESOURCE.getValue());
5323 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5324 log.debug(CATEGORY_IS_EMPTY);
5325 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5326 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5327 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5328 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
5329 ComponentTypeEnum.RESOURCE.getValue());
5332 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
5335 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
5336 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5337 ResponseFormat responseFormat;
5338 if (category != null && subcategory != null) {
5339 log.debug("validating resource category {} against valid categories list", category);
5340 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5341 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5342 if (categories.isRight()) {
5343 log.debug("failed to retrieve resource categories from JanusGraph");
5344 responseFormat = componentsUtils.getResponseFormat(categories.right()
5346 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5347 throw new ByActionStatusComponentException(categories.right()
5350 List<CategoryDefinition> categoryList = categories.left()
5352 Optional<CategoryDefinition> foundCategory = categoryList.stream()
5353 .filter(cat -> cat.getName()
5354 .equals(category.getName()))
5356 if (!foundCategory.isPresent()) {
5357 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5358 category, categoryList);
5359 failOnInvalidCategory(user, resource, actionEnum);
5361 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
5364 .filter(subcat -> subcat.getName()
5365 .equals(subcategory.getName()))
5367 if (!foundSubcategory.isPresent()) {
5369 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5370 subcategory, foundCategory.get()
5371 .getSubcategories());
5372 failOnInvalidCategory(user, resource, actionEnum);
5377 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
5378 ResponseFormat responseFormat;
5379 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5380 ComponentTypeEnum.RESOURCE.getValue());
5381 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5382 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5385 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
5386 String vendorRelease = resource.getVendorRelease();
5387 log.debug("validate vendor relese name");
5388 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5389 log.info("vendor relese name is missing.");
5390 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5391 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5392 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
5395 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
5398 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
5399 AuditingActionEnum actionEnum) {
5400 if (vendorRelease != null) {
5401 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
5402 log.info("vendor release exceds limit.");
5403 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5404 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5405 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5406 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
5407 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5410 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
5411 log.info("vendor release is not valid.");
5412 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
5413 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5414 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
5419 private void validateVendorName(User user, Resource resource,
5420 AuditingActionEnum actionEnum) {
5421 String vendorName = resource.getVendorName();
5422 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
5423 log.info("vendor name is missing.");
5424 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
5425 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5426 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
5428 validateVendorName(vendorName, user, resource, actionEnum);
5431 private void validateVendorName(String vendorName, User user, Resource resource,
5432 AuditingActionEnum actionEnum) {
5433 if (vendorName != null) {
5434 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
5435 log.info("vendor name exceds limit.");
5436 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5437 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5438 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5439 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5440 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5443 if (!ValidationUtils.validateVendorName(vendorName)) {
5444 log.info("vendor name is not valid.");
5445 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
5446 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5447 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME, vendorName);
5452 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
5453 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
5454 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
5455 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
5456 log.info("resource vendor model number exceeds limit.");
5457 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5458 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5459 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5460 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5461 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5462 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5464 // resource vendor model number is currently validated as vendor
5466 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
5467 log.info("resource vendor model number is not valid.");
5468 ResponseFormat errorResponse = componentsUtils
5469 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5470 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5471 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5477 private void validateCost(Resource resource) {
5478 String cost = resource.getCost();
5480 if (!ValidationUtils.validateCost(cost)) {
5481 log.debug("resource cost is invalid.");
5482 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5487 private void validateLicenseType(User user, Resource resource,
5488 AuditingActionEnum actionEnum) {
5489 log.debug("validate licenseType");
5490 String licenseType = resource.getLicenseType();
5491 if (licenseType != null) {
5492 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
5494 if (!licenseTypes.contains(licenseType)) {
5495 log.debug("License type {} isn't configured", licenseType);
5496 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5497 if (actionEnum != null) {
5498 // In update case, no audit is required
5499 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5501 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5506 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
5507 Resource updatedResource, String userId, boolean inTransaction) {
5508 Either<Operation, ResponseFormat> deleteArtifactByInterface;
5509 if (updatedResource.getDerivedFrom() != null) {
5510 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
5511 log.debug("1. Removing interface artifacts from graph");
5512 // Remove all interface artifacts of resource
5513 String resourceId = updatedResource.getUniqueId();
5514 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
5516 if (interfaces != null) {
5517 Collection<InterfaceDefinition> values = interfaces.values();
5518 for (InterfaceDefinition interfaceDefinition : values) {
5519 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
5521 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
5522 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
5523 if (operations != null) {
5524 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
5525 Operation operation = operationEntry.getValue();
5526 ArtifactDefinition implementation = operation.getImplementationArtifact();
5527 if (implementation != null) {
5528 String uniqueId = implementation.getUniqueId();
5529 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
5530 uniqueId, operationEntry.getKey(), interfaceType);
5531 // only thing that transacts and locks here
5532 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
5533 userId, uniqueId, true);
5534 if (deleteArtifactByInterface.isRight()) {
5535 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
5536 if (!inTransaction) {
5537 janusGraphDao.rollback();
5539 return Either.right(deleteArtifactByInterface.right()
5543 log.trace("No implementation found for operation {} - nothing to delete",
5544 operationEntry.getKey());
5548 log.trace("No operations found for interface type {}", interfaceType);
5552 log.debug("2. Removing properties");
5553 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
5554 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
5556 if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
5557 log.debug("Failed to remove all properties of resource");
5558 if (!inTransaction) {
5559 janusGraphDao.rollback();
5561 return Either.right(componentsUtils
5562 .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
5567 log.debug("Derived from wasn't changed during update");
5570 if (inTransaction) {
5571 return Either.left(true);
5573 janusGraphDao.commit();
5574 return Either.left(true);
5578 /**** Auditing *******************/
5580 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
5581 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
5582 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
5584 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
5586 return webApplicationContext.getBean(class1);
5589 public ICapabilityTypeOperation getCapabilityTypeOperation() {
5590 return capabilityTypeOperation;
5594 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
5595 this.capabilityTypeOperation = capabilityTypeOperation;
5598 public Boolean validatePropertiesDefaultValues(Resource resource) {
5599 log.debug("validate resource properties default values");
5600 List<PropertyDefinition> properties = resource.getProperties();
5601 if (properties != null) {
5602 iterateOverProperties(properties);
5607 public void iterateOverProperties(List<PropertyDefinition> properties) {
5609 String innerType = null;
5610 for (PropertyDefinition property : properties) {
5611 if (!propertyOperation.isPropertyTypeValid(property)) {
5612 log.info("Invalid type for property {}", property);
5613 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
5614 property.getType(), property.getName());
5617 Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
5618 type = property.getType();
5620 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5621 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
5622 if (responseFormat != null) {
5626 validateDefaultPropertyValue(property, allDataTypes, type, innerType);
5630 private void validateDefaultPropertyValue(PropertyDefinition property,
5631 Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
5632 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
5633 log.info("Invalid default value for property {}", property);
5634 ResponseFormat responseFormat;
5635 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5636 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
5637 property.getName(), type, innerType, property.getDefaultValue());
5639 throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
5640 property.getName(), type, property.getDefaultValue());
5644 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
5645 Map<String, DataTypeDefinition> allDataTypes) {
5646 ResponseFormat responseFormat = null;
5647 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
5649 innerType = propertyInnerTypeValid.getLeft();
5650 if (!propertyInnerTypeValid.getRight()
5652 log.info("Invalid inner type for property {}", property);
5653 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
5654 property.getName());
5656 return responseFormat;
5660 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
5661 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
5665 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
5666 return componentInstanceBusinessLogic;
5669 private String getComponentTypeForResponse(Component component) {
5670 String componentTypeForResponse = "SERVICE";
5671 if (component instanceof Resource) {
5672 componentTypeForResponse = ((Resource) component).getResourceType()
5675 return componentTypeForResponse;
5678 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
5681 validateUserExists(user);
5683 // get resource from csar uuid
5684 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
5685 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
5686 if (either.isRight()) {
5687 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
5689 return Either.right(resp);
5692 return Either.left(either.left()
5697 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5698 String componentId, String userId) {
5702 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
5703 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5704 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5706 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5707 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
5708 defaultCapabilities, validCapabilitiesMap));
5709 return validCapabilitiesMap;
5712 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
5713 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5714 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
5715 String capabilityType = capabilities.get(0)
5717 if (defaultCapabilities.containsKey(capabilityType)) {
5718 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5719 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5720 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5721 validCapabilityList.add(defaultCapability);
5722 validCapabilitiesMap.put(key, validCapabilityList);
5724 throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
5728 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
5729 CapabilityDefinition defaultCapability) {
5730 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
5731 .getProperties())) {
5732 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5733 defaultCapability.getName(), resourceId);
5734 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
5735 defaultCapability.getName());
5736 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
5737 } else if (isNotEmpty(capabilities.get(0)
5738 .getProperties())) {
5739 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5743 private CapabilityDefinition getCapability(String resourceId,
5744 Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5745 CapabilityDefinition defaultCapability;
5746 if (isNotEmpty(defaultCapabilities.get(capabilityType)
5748 .getProperties())) {
5749 defaultCapability = defaultCapabilities.get(capabilityType)
5752 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5753 .getToscaFullElement(resourceId);
5754 if (getFullComponentRes.isRight()) {
5755 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
5757 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
5759 defaultCapability = getFullComponentRes.left()
5762 .get(capabilityType)
5765 return defaultCapability;
5768 private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
5769 UploadCapInfo uploadedCapability) {
5770 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5771 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
5773 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5774 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5775 for (UploadPropInfo property : uploadedProperties) {
5776 String propertyName = property.getName()
5778 String propertyType = property.getType();
5779 ComponentInstanceProperty validProperty;
5780 if (defaultProperties.containsKey(propertyName)
5781 && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5782 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
5784 validProperty = new ComponentInstanceProperty();
5785 validProperty.setName(propertyName);
5786 if (property.getValue() != null) {
5787 validProperty.setValue(property.getValue()
5790 validProperty.setDescription(property.getDescription());
5791 validProperty.setPassword(property.isPassword());
5792 validProperties.add(validProperty);
5794 defaultCapability.setProperties(validProperties);
5797 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
5798 String propertyType) {
5799 return propertyType != null && !defaultProperties.get(propertyName)
5801 .equals(propertyType);
5804 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5805 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5806 Resource resource, User user) {
5808 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5809 ArtifactOperationEnum.class);
5810 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5811 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5812 .left(nodeTypeArtifactsToHandle);
5814 // add all found Csar artifacts to list to upload
5815 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5816 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5817 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5818 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5819 ArtifactDefinition foundArtifact;
5821 if (!existingArtifactsToHandle.isEmpty()) {
5822 foundArtifact = existingArtifactsToHandle.stream()
5823 .filter(a -> a.getArtifactName()
5824 .equals(currNewArtifact.getArtifactName()))
5827 if (foundArtifact != null) {
5828 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
5829 if (!foundArtifact.getArtifactChecksum()
5830 .equals(currNewArtifact.getArtifactChecksum())) {
5831 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5832 // if current artifact already exists, but has
5833 // different content, add him to the list to
5835 artifactsToUpdate.add(currNewArtifact);
5837 // remove found artifact from the list of existing
5838 // artifacts to handle, because it was already
5840 existingArtifactsToHandle.remove(foundArtifact);
5841 // and remove found artifact from the list to
5842 // upload, because it should either be updated or be
5844 artifactsToUpload.remove(currNewArtifact);
5846 log.debug("Can't upload two artifact with the same name {}.",
5847 currNewArtifact.getArtifactName());
5848 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
5849 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5850 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
5851 foundArtifact.getArtifactType());
5852 AuditingActionEnum auditingAction = artifactsBusinessLogic
5853 .detectAuditingType(new ArtifactOperationInfo(false, false,
5854 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5855 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5856 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5857 resource.getComponentType(), null);
5858 responseWrapper.setInnerElement(responseFormat);
5864 if (responseWrapper.isEmpty()) {
5865 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5866 if (currArtifact.getIsFromCsar()) {
5867 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5868 currArtifact.getArtifactType(),
5869 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5870 currArtifact.getIsFromCsar()));
5872 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5873 currArtifact.getArtifactType(),
5874 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5875 currArtifact.getIsFromCsar()));
5880 if (responseWrapper.isEmpty()) {
5881 if (!artifactsToUpload.isEmpty()) {
5882 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5884 if (!artifactsToUpdate.isEmpty()) {
5885 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5887 if (!artifactsToDelete.isEmpty()) {
5888 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5891 if (!responseWrapper.isEmpty()) {
5892 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5894 } catch (Exception e) {
5895 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5896 responseWrapper.setInnerElement(responseFormat);
5897 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5899 return nodeTypeArtifactsToHandleRes;
5902 ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
5903 final String vfResourceName,
5904 final String nodeTypeFullName) {
5906 String actualVfName;
5907 if (ResourceTypeEnum.CVFC.name()
5908 .equals(nodeResourceType)) {
5909 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5910 actualType = ResourceTypeEnum.VFC.name();
5912 actualVfName = vfResourceName;
5913 actualType = nodeResourceType;
5915 String nameWithouNamespacePrefix;
5917 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
5918 log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
5919 + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName,
5920 nodeTypeFullName, actualType, vfResourceName);
5921 final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
5923 if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
5924 nameWithouNamespacePrefix = nodeTypeFullName;
5926 nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
5928 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5930 if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
5931 actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
5933 actualName = "." + nameWithouNamespacePrefix;
5936 if (actualName.startsWith(Constants.ABSTRACT)) {
5937 toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
5938 .append(ValidationUtils.convertToSystemName(actualVfName));
5940 toscaResourceName.append(actualType.toLowerCase()).append('.')
5941 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5943 final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5944 final String[] actualNames = actualName.split("\\.");
5945 if (actualNames.length < 3) {
5946 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5947 previousToscaResourceName.append(actualName).toString());
5949 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5950 previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
5951 .toLowerCase()).toString());
5952 } catch (final Exception e) {
5953 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5954 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5959 * Extracts a Node Type Name prefix from the given Node Type Name.
5961 * @param fullName Node Type Name
5962 * @return Node Type Name Prefix
5964 private String getNodeTypeNamePrefix(final String fullName) {
5965 String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
5966 final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
5967 log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
5968 final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
5969 if (validNameSpace.isPresent()) {
5970 tempPrefix = validNameSpace.get();
5972 log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
5977 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
5978 List<String> dataParamsToReturn) {
5980 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5981 Either<Resource, StorageOperationStatus> resourceResultEither =
5982 toscaOperationFacade.getToscaElement(resourceId,
5985 if (resourceResultEither.isRight()) {
5986 if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
5987 log.debug("Failed to found resource with id {} ", resourceId);
5989 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5992 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5993 return Either.right(componentsUtils
5994 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
5998 Resource resource = resourceResultEither.left().value();
5999 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
6000 ListUtils.emptyIfNull(resource.getInputs())
6001 .forEach(input -> input.setConstraints(setInputConstraint(input)));
6004 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
6005 dataParamsToReturn);
6006 return Either.left(dataTransfer);
6010 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
6011 Resource resource = (Resource) clonedComponent;
6012 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
6013 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
6014 .shouldUpgradeToLatestDerived(resource);
6015 if (shouldUpgradeToLatestDerived.isRight()) {
6016 return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
6019 return Either.left(shouldUpgradeToLatestDerived.left()
6022 return super.shouldUpgradeToLatestDerived(clonedComponent);