2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import static java.util.stream.Collectors.joining;
24 import static java.util.stream.Collectors.toList;
25 import static java.util.stream.Collectors.toMap;
26 import static java.util.stream.Collectors.toSet;
27 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
28 import static org.apache.commons.collections.MapUtils.isEmpty;
29 import static org.apache.commons.collections.MapUtils.isNotEmpty;
30 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
31 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
32 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
33 import static org.openecomp.sdc.common.api.Constants.DEFAULT_GROUP_VF_MODULE;
35 import com.google.common.annotations.VisibleForTesting;
36 import fj.data.Either;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.EnumMap;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.ListIterator;
47 import java.util.Map.Entry;
48 import java.util.Optional;
50 import java.util.function.Function;
51 import java.util.regex.Pattern;
52 import java.util.stream.Collectors;
53 import javax.servlet.ServletContext;
54 import org.apache.commons.codec.binary.Base64;
55 import org.apache.commons.collections.CollectionUtils;
56 import org.apache.commons.collections.MapUtils;
57 import org.apache.commons.collections4.ListUtils;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.commons.lang3.tuple.ImmutablePair;
60 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
61 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
62 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
63 import org.openecomp.sdc.be.components.csar.CsarInfo;
64 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
65 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
66 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
67 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
68 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
69 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
70 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
71 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
72 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
73 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
74 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
75 import org.openecomp.sdc.be.components.merge.TopologyComparator;
76 import org.openecomp.sdc.be.components.merge.property.PropertyDataValueMergeBusinessLogic;
77 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
78 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
79 import org.openecomp.sdc.be.components.property.PropertyConstraintsUtils;
80 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
81 import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator;
82 import org.openecomp.sdc.be.components.validation.component.ComponentIconValidator;
83 import org.openecomp.sdc.be.components.validation.component.ComponentNameValidator;
84 import org.openecomp.sdc.be.components.validation.component.ComponentProjectCodeValidator;
85 import org.openecomp.sdc.be.components.validation.component.ComponentTagsValidator;
86 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
87 import org.openecomp.sdc.be.config.BeEcompErrorManager;
88 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
89 import org.openecomp.sdc.be.config.ConfigurationManager;
90 import org.openecomp.sdc.be.dao.api.ActionStatus;
91 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
92 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
93 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
94 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
95 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
96 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
97 import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
98 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
99 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
100 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
101 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
102 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
103 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
104 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
105 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
106 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
107 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
108 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
109 import org.openecomp.sdc.be.impl.ComponentsUtils;
110 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
111 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
112 import org.openecomp.sdc.be.model.ArtifactDefinition;
113 import org.openecomp.sdc.be.model.AttributeDefinition;
114 import org.openecomp.sdc.be.model.CapabilityDefinition;
115 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
116 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
117 import org.openecomp.sdc.be.model.Component;
118 import org.openecomp.sdc.be.model.ComponentInstance;
119 import org.openecomp.sdc.be.model.ComponentInstanceInput;
120 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
121 import org.openecomp.sdc.be.model.ComponentParametersView;
122 import org.openecomp.sdc.be.model.DataTypeDefinition;
123 import org.openecomp.sdc.be.model.GroupDefinition;
124 import org.openecomp.sdc.be.model.InputDefinition;
125 import org.openecomp.sdc.be.model.InterfaceDefinition;
126 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
127 import org.openecomp.sdc.be.model.LifecycleStateEnum;
128 import org.openecomp.sdc.be.model.NodeTypeInfo;
129 import org.openecomp.sdc.be.model.Operation;
130 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
131 import org.openecomp.sdc.be.model.PolicyDefinition;
132 import org.openecomp.sdc.be.model.PropertyDefinition;
133 import org.openecomp.sdc.be.model.RelationshipImpl;
134 import org.openecomp.sdc.be.model.RelationshipInfo;
135 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
136 import org.openecomp.sdc.be.model.RequirementDefinition;
137 import org.openecomp.sdc.be.model.Resource;
138 import org.openecomp.sdc.be.model.UploadArtifactInfo;
139 import org.openecomp.sdc.be.model.UploadCapInfo;
140 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
141 import org.openecomp.sdc.be.model.UploadInfo;
142 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
143 import org.openecomp.sdc.be.model.UploadPropInfo;
144 import org.openecomp.sdc.be.model.UploadReqInfo;
145 import org.openecomp.sdc.be.model.UploadResourceInfo;
146 import org.openecomp.sdc.be.model.User;
147 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
148 import org.openecomp.sdc.be.model.category.CategoryDefinition;
149 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
150 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
151 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
152 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
153 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
154 import org.openecomp.sdc.be.model.operations.StorageException;
155 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
156 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
157 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
158 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
159 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
160 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
161 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
162 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
163 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
164 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
165 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
166 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
167 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
168 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
169 import org.openecomp.sdc.be.tosca.CsarUtils;
170 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
171 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
172 import org.openecomp.sdc.be.user.UserBusinessLogic;
173 import org.openecomp.sdc.be.utils.CommonBeUtils;
174 import org.openecomp.sdc.be.utils.TypeUtils;
175 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
176 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
177 import org.openecomp.sdc.common.api.Constants;
178 import org.openecomp.sdc.common.datastructure.Wrapper;
179 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
180 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
181 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
182 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
183 import org.openecomp.sdc.common.log.enums.StatusCode;
184 import org.openecomp.sdc.common.log.wrappers.Logger;
185 import org.openecomp.sdc.common.util.GeneralUtility;
186 import org.openecomp.sdc.common.util.ValidationUtils;
187 import org.openecomp.sdc.exception.ResponseFormat;
188 import org.springframework.beans.factory.annotation.Autowired;
189 import org.springframework.context.annotation.Lazy;
190 import org.springframework.web.context.WebApplicationContext;
191 import org.yaml.snakeyaml.DumperOptions;
192 import org.yaml.snakeyaml.Yaml;
194 @org.springframework.stereotype.Component("resourceBusinessLogic")
195 public class ResourceBusinessLogic extends ComponentBusinessLogic {
197 private static final String DELETE_RESOURCE = "Delete Resource";
198 private static final String IN_RESOURCE = " in resource {} ";
199 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
200 public static final String INITIAL_VERSION = "0.1";
201 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
202 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
203 private static final String CREATE_RESOURCE = "Create Resource";
204 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
205 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
206 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
207 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
208 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
209 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
212 private IInterfaceLifecycleOperation interfaceTypeOperation;
213 private LifecycleBusinessLogic lifecycleBusinessLogic;
215 private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
216 private final ResourceImportManager resourceImportManager;
217 private final InputsBusinessLogic inputsBusinessLogic;
218 private final CompositionBusinessLogic compositionBusinessLogic;
219 private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
220 private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
221 private final MergeInstanceUtils mergeInstanceUtils;
222 private final UiComponentDataConverter uiComponentDataConverter;
223 private final CsarBusinessLogic csarBusinessLogic;
224 private final PropertyBusinessLogic propertyBusinessLogic;
225 private final PolicyBusinessLogic policyBusinessLogic;
228 public ResourceBusinessLogic(IElementOperation elementDao,
229 IGroupOperation groupOperation,
230 IGroupInstanceOperation groupInstanceOperation,
231 IGroupTypeOperation groupTypeOperation,
232 GroupBusinessLogic groupBusinessLogic,
233 InterfaceOperation interfaceOperation,
234 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
235 ArtifactsBusinessLogic artifactsBusinessLogic,
236 ComponentInstanceBusinessLogic componentInstanceBusinessLogic, @Lazy ResourceImportManager resourceImportManager,
237 InputsBusinessLogic inputsBusinessLogic, CompositionBusinessLogic compositionBusinessLogic,
238 ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
239 CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic, MergeInstanceUtils mergeInstanceUtils,
240 UiComponentDataConverter uiComponentDataConverter, CsarBusinessLogic csarBusinessLogic,
241 ArtifactsOperations artifactToscaOperation, PropertyBusinessLogic propertyBusinessLogic,
242 ComponentContactIdValidator componentContactIdValidator,
243 ComponentNameValidator componentNameValidator, ComponentTagsValidator componentTagsValidator,
244 ComponentValidator componentValidator,
245 ComponentIconValidator componentIconValidator,
246 ComponentProjectCodeValidator componentProjectCodeValidator,
247 ComponentDescriptionValidator componentDescriptionValidator, PolicyBusinessLogic policyBusinessLogic) {
248 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
249 interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation,
250 componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
251 componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
252 this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
253 this.resourceImportManager = resourceImportManager;
254 this.inputsBusinessLogic = inputsBusinessLogic;
255 this.compositionBusinessLogic = compositionBusinessLogic;
256 this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
257 this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
258 this.mergeInstanceUtils = mergeInstanceUtils;
259 this.uiComponentDataConverter = uiComponentDataConverter;
260 this.csarBusinessLogic = csarBusinessLogic;
261 this.propertyBusinessLogic = propertyBusinessLogic;
262 this.policyBusinessLogic = policyBusinessLogic;
266 private ICapabilityTypeOperation capabilityTypeOperation;
269 private TopologyComparator topologyComparator;
272 private ComponentValidator componentValidator;
275 private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
278 private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
280 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
281 return lifecycleBusinessLogic;
285 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
286 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
290 protected void setComponentValidator(ComponentValidator componentValidator) {
291 this.componentValidator = componentValidator;
294 public IElementOperation getElementDao() {
298 public void setElementDao(IElementOperation elementDao) {
299 this.elementDao = elementDao;
302 public UserBusinessLogic getUserAdmin() {
303 return this.userAdmin;
307 public void setUserAdmin(UserBusinessLogic userAdmin) {
308 this.userAdmin = userAdmin;
311 public ComponentsUtils getComponentsUtils() {
312 return this.componentsUtils;
316 public void setComponentsUtils(ComponentsUtils componentsUtils) {
317 this.componentsUtils = componentsUtils;
320 public ArtifactsBusinessLogic getArtifactsManager() {
321 return artifactsBusinessLogic;
324 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
325 this.artifactsBusinessLogic = artifactsManager;
328 public ApplicationDataTypeCache getApplicationDataTypeCache() {
329 return applicationDataTypeCache;
333 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
334 this.applicationDataTypeCache = applicationDataTypeCache;
338 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
339 this.interfaceTypeOperation = interfaceTypeOperation;
343 * the method returns a list of all the resources that are certified, the
344 * returned resources are only abstract or only none abstract according to
352 public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter,
354 User user = validateUserExists(userId);
355 Boolean isHighest = null;
356 switch (highestFilter) {
362 case NON_HIGHEST_ONLY:
368 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
369 .getAllCertifiedResources(getAbstract, isHighest);
371 if (getResponse.isRight()) {
372 throw new StorageException(getResponse.right()
376 return getResponse.left()
380 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
381 ResourceTypeEnum resourceTypeEnum, String userId) {
383 validateUserExists(userId);
385 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
386 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
388 janusGraphDao.commit();
390 if (dataModelResponse.isLeft()) {
391 Map<String, Boolean> result = new HashMap<>();
392 result.put("isValid", dataModelResponse.left()
394 log.debug("validation was successfully performed.");
395 return Either.left(result);
398 ResponseFormat responseFormat = componentsUtils
399 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
402 return Either.right(responseFormat);
405 public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user,
406 Map<String, byte[]> csarUIPayload, String payloadName) {
407 validateResourceBeforeCreate(resource, user, false);
408 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
409 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId());
410 if (StringUtils.isNotEmpty(csarUUID)) {
411 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
412 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
414 Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
415 return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left()
416 .map(r -> (Resource) r)
421 final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
422 return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left()
423 .map(r -> (Resource) r)
428 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
429 String payloadName, String resourceUniqueId) {
430 String csarUUID = payloadName;
431 String csarVersion = null;
432 Resource updatedResource = null;
433 if (payloadName == null) {
434 csarUUID = resource.getCsarUUID();
435 csarVersion = resource.getCsarVersion();
437 if (csarUUID != null && !csarUUID.isEmpty()) {
438 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
439 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
440 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
441 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
442 overrideImmutableMetadata(oldResource, resource);
444 validateResourceBeforeCreate(resource, user, false);
445 String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null;
446 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
448 // (on boarding flow): If the update includes same csarUUID and
449 // same csarVersion as already in the VF - no need to import the
450 // csar (do only metadata changes if there are).
451 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
452 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
454 updatedResource = updateResourceFromCsar(oldResource, resource, user,
455 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
458 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
459 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
461 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
462 throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
464 return updatedResource;
467 private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
468 // (on boarding flow): If the update includes a csarUUID: verify this
469 // csarUUID is not in use by another VF, If it is - use same error as
471 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
472 // select another or update the existing VF." %1 - csarUUID, %2 - VF
474 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
475 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
476 if (resourceLinkedToCsarRes.isRight()) {
477 if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
478 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
479 resource.getSystemName());
480 throw new StorageException(resourceLinkedToCsarRes.right()
483 } else if (!resourceLinkedToCsarRes.left()
486 .equals(oldResource.getUniqueId())
487 && !resourceLinkedToCsarRes.left()
490 .equals(oldResource.getName())) {
491 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
492 resourceLinkedToCsarRes.left()
495 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
496 throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left()
502 private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID,
503 String resourceUniqueId, User user) {
504 // (on boarding flow): If the update includes csarUUID which is
505 // different from the csarUUID of the VF - fail with
506 // error: "Error: Resource %1 cannot be updated using since it is linked
507 // to a different VSP" %1 - VF name
508 String oldCsarUUID = oldResource.getCsarUUID();
509 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
511 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
512 resourceUniqueId, csarUUID, oldCsarUUID);
513 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
514 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
515 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
516 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID,
521 private Resource getResourceByUniqueId(String resourceUniqueId) {
522 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade
523 .getToscaFullElement(resourceUniqueId);
524 if (oldResourceRes.isRight()) {
525 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
526 oldResourceRes.right()
528 throw new StorageException(oldResourceRes.right()
531 return oldResourceRes.left()
535 private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
536 resource.setName(oldResource.getName());
537 resource.setIcon(oldResource.getIcon());
538 resource.setTags(oldResource.getTags());
539 resource.setCategories(oldResource.getCategories());
540 resource.setDerivedFrom(oldResource.getDerivedFrom());
543 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user,
544 AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload,
546 Resource updatedResource = null;
547 validateLifecycleState(oldResource, user);
548 String lockedResourceId = oldResource.getUniqueId();
549 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
550 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
551 lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
553 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
555 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
556 nodeTypesInfo, csarInfo, oldResource);
557 if (findNodeTypesArtifactsToHandleRes.isRight()) {
558 log.debug("failed to find node types for update with artifacts during import csar {}. ",
559 csarInfo.getCsarUUID());
560 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right()
563 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
567 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts,
568 csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo,
569 nodeTypesArtifactsToHandle, null, false);
571 } catch (ComponentException | StorageException e) {
572 rollback(inTransaction, newResource, createdArtifacts, null);
576 janusGraphDao.commit();
577 log.debug("unlock resource {}", lockedResourceId);
578 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
580 return updatedResource;
584 private void validateLifecycleState(Resource oldResource, User user) {
585 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState()
586 && !oldResource.getLastUpdaterUserId()
587 .equals(user.getUserId())) {
589 "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
590 oldResource.getLastUpdaterUserId(), user.getUserId());
591 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
595 private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
596 List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
597 Map<String, NodeTypeInfo> nodeTypesInfo,
598 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
599 String nodeName, boolean isNested) {
600 boolean inTransaction = true;
601 boolean shouldLock = false;
602 Resource preparedResource = null;
603 ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
605 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName,
606 nodeTypesInfo, csarInfo, nodeName, oldResource);
607 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
608 if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
609 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
611 preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(),
612 inTransaction, shouldLock, isNested).left;
613 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
614 handleResourceGenericType(preparedResource);
615 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle,
616 createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
617 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
618 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
619 preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
620 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames);
621 } catch (ComponentException e) {
622 ResponseFormat responseFormat = e.getResponseFormat() == null
623 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
624 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
626 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
627 preparedResource == null ? oldResource : preparedResource, actionEnum);
629 } catch (StorageException e) {
630 ResponseFormat responseFormat = componentsUtils
631 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
632 log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
634 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
635 preparedResource == null ? oldResource : preparedResource, actionEnum);
638 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
639 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
640 preparedResource.getSystemName());
641 if (validateUpdateVfGroupNamesRes.isRight()) {
643 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right()
646 // add groups to newResource
647 Map<String, GroupDefinition> groups;
649 if (!validateUpdateVfGroupNamesRes.left()
652 groups = validateUpdateVfGroupNamesRes.left()
655 groups = uploadComponentInstanceInfoMap.getGroups();
657 handleGroupsProperties(preparedResource, groups);
658 Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
660 preparedResource = updateGroupsOnResource(preparedResource, groups);
662 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
663 nodeTypesArtifactsToHandle);
665 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE,
666 createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts,
667 inTransaction, shouldLock);
668 if (updateArtifactsEither.isRight()) {
669 log.debug("failed to update artifacts {}", updateArtifactsEither.right()
671 throw new ByResponseFormatComponentException(updateArtifactsEither.right()
674 preparedResource = getResourceWithGroups(updateArtifactsEither.left()
678 updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
679 updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
681 final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
682 preparedResource = getResourceWithGroups(preparedResourceId);
684 updateVolumeGroup(preparedResource);
686 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
687 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
688 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
690 throw new ByResponseFormatComponentException(responseFormat);
692 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
694 return preparedResource;
697 protected void updateVolumeGroup(Resource preparedResource) {
698 List<GroupDefinition> groups = preparedResource.safeGetGroups();
699 for (GroupDefinition group : groups) {
700 Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
701 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
702 List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
703 if (!volumePropList.isEmpty()) {
704 PropertyDataDefinition volumeProp = volumePropList.get(0);
705 if (volumeProp != null) {
706 boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
708 if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
709 volumeProp.setValue(String.valueOf(isVolumeGroup));
710 volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
718 private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
719 if (oldResource == null || preparedResource == null) {
720 log.debug("Failed to update groups name : oldResource or preparedResource is null");
721 } else if (CollectionUtils.isNotEmpty(oldResource.getGroups())
722 && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
723 Map<String, String> oldGroups = oldResource.getGroups()
725 .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
727 List<GroupDefinition> updatedGroups = preparedResource.getGroups()
729 .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
730 .equals(oldGroups.get(group.getInvariantName())))
733 if (CollectionUtils.isNotEmpty(updatedGroups)) {
734 if (isTopologyChanged) {
735 updatedGroups.stream().filter(group -> !group.isVspOriginated())
736 .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
738 updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
740 groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
745 private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource,
746 boolean isTopologyChanged) {
747 if (oldResource == null || preparedResource == null) {
748 log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
750 if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
751 Map<String, String> oldInstances = oldResource.getComponentInstances()
753 .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
754 List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
756 .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
757 .equals(oldInstances.get(i.getInvariantName())))
759 if (CollectionUtils.isNotEmpty(updatedInstances)) {
760 if (isTopologyChanged) {
761 updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
762 .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
764 updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
769 componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
770 null, preparedResource.getUniqueId(), csarInfo.getModifier()
772 preparedResource.getComponentInstances(), false);
776 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
777 List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
778 Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
779 boolean inTransaction, boolean shouldLock) {
781 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
782 Resource resource = preparedResource;
784 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
785 .getNodeTypesArtifactsToHandle();
786 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
787 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
788 && !nodeTypesArtifactsToHandle.get(nodeName)
790 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
791 preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
792 csarInfo.getModifier(), inTransaction, true);
793 if (handleNodeTypeArtifactsRes.isRight()) {
794 return Either.right(handleNodeTypeArtifactsRes.right()
799 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
800 csarInfo, createdArtifacts,
801 new ArtifactOperationInfo(false, false, operation), shouldLock,
803 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
804 if (createdCsarArtifactsEither.isRight()) {
805 return createdCsarArtifactsEither;
808 resource = createdCsarArtifactsEither.left()
811 return Either.left(resource);
814 private Resource handleResourceGenericType(Resource resource) {
815 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
816 if (resource.shouldGenerateInputs()) {
817 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
819 return genericResource;
822 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
823 final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
825 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
826 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
827 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
830 final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
831 .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
832 final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
833 nodeTypesInfo, oldResource.getName(), csarInfo);
834 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
835 oldResource.getName(), csarInfo.getCsarUUID());
836 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
837 nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
838 } catch (Exception e) {
839 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
840 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
841 log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
843 return nodeTypesArtifactsToHandleRes;
846 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
847 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
848 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
849 ImmutablePair<String, String> vfcToscaNames) {
851 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
852 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
853 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
855 if (!isEmpty(extractedVfcsArtifacts)) {
856 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
857 if (extractedVfcsArtifacts.containsKey(namespace)) {
858 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
860 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
861 } else if (curNodeType != null) {
862 // delete all artifacts if have not received artifacts from
864 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
865 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
866 // delete all informational artifacts
867 artifactsToDelete.addAll(curNodeType.getArtifacts()
870 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
872 // delete all deployment artifacts
873 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
875 if (!artifactsToDelete.isEmpty()) {
876 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
879 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
880 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
884 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
885 String previousVfcToscaName, StorageOperationStatus status) {
886 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
887 log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
889 ResponseFormat responseFormat = componentsUtils
890 .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
891 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
892 AuditingActionEnum.CREATE_RESOURCE);
893 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
894 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
895 return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
897 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
902 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
903 List<ArtifactDefinition> extractedArtifacts) {
905 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
907 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
908 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
909 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
910 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
911 artifactsToDelete, collectExistingArtifacts(curNodeType));
912 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
913 } catch (Exception e) {
914 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
915 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
917 return nodeTypeArtifactsToHandle;
920 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
921 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
922 List<ArtifactDefinition> artifactsToDelete) {
923 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
924 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
925 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
926 if (!artifactsToUpload.isEmpty()) {
927 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
929 if (!artifactsToUpdate.isEmpty()) {
930 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
932 if (!artifactsToDelete.isEmpty()) {
933 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
936 return nodeTypeArtifactsToHandle;
939 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
940 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
941 List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
942 if (!existingArtifacts.isEmpty()) {
943 extractedArtifacts.stream()
944 .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
945 artifactsToDelete.addAll(existingArtifacts.values());
949 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
950 List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
951 ArtifactDefinition currNewArtifact) {
952 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
954 .filter(a -> a.getArtifactName()
955 .equals(currNewArtifact.getArtifactName()))
957 if (foundArtifact.isPresent()) {
958 if (foundArtifact.get()
960 .equals(currNewArtifact.getArtifactType())) {
961 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
962 existingArtifacts.remove(foundArtifact.get()
963 .getArtifactLabel());
964 artifactsToUpload.remove(currNewArtifact);
966 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
967 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
968 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
974 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
975 ArtifactDefinition foundArtifact) {
976 if (!foundArtifact.getArtifactChecksum()
977 .equals(currNewArtifact.getArtifactChecksum())) {
978 foundArtifact.setPayload(currNewArtifact.getPayloadData());
979 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
980 foundArtifact.setArtifactChecksum(
981 GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
982 artifactsToUpdate.add(foundArtifact);
986 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
987 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
988 if (curNodeType == null) {
989 return existingArtifacts;
991 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
992 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
994 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
995 existingArtifacts.putAll(curNodeType.getArtifacts()
998 .filter(e -> e.getValue()
999 .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
1000 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
1002 return existingArtifacts;
1006 * Changes resource life cycle state to checked out
1010 * @param inTransaction
1013 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
1014 Either<Resource, ResponseFormat> checkoutResourceRes;
1016 if (!resource.getComponentMetadataDefinition()
1017 .getMetadataDataDefinition()
1019 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
1021 "************* Going to change life cycle state of resource {} to not certified checked out. ",
1022 resource.getName());
1023 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
1024 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
1025 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1026 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
1027 inTransaction, true);
1028 if (checkoutRes.isRight()) {
1029 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
1030 resource.getComponentType()
1032 resource.getUniqueId(), checkoutRes.right()
1035 checkoutResourceRes = Either.right(checkoutRes.right()
1038 checkoutResourceRes = Either.left((Resource) checkoutRes.left()
1042 checkoutResourceRes = Either.left(resource);
1044 } catch (Exception e) {
1045 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1046 checkoutResourceRes = Either.right(responseFormat);
1047 log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
1050 return checkoutResourceRes;
1054 * Handles Artifacts of NodeType
1056 * @param nodeTypeResource
1057 * @param nodeTypeArtifactsToHandle
1059 * @param inTransaction
1062 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
1063 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1064 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
1065 List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
1066 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1067 Either<Resource, ResponseFormat> changeStateResponse;
1069 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1070 if (changeStateResponse.isRight()) {
1071 return Either.right(changeStateResponse.right()
1074 nodeTypeResource = changeStateResponse.left()
1077 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1078 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1079 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1081 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1082 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1083 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1084 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
1085 nodeTypeResource.getName());
1086 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1087 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
1088 createdArtifacts, new ArtifactOperationInfo(false,
1089 ignoreLifecycleState, curOperation),
1090 false, inTransaction);
1091 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1092 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1094 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
1097 if (handleNodeTypeArtifactsRes == null) {
1098 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1100 } catch (Exception e) {
1101 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1102 handleNodeTypeArtifactsRes = Either.right(responseFormat);
1103 log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1105 return handleNodeTypeArtifactsRes;
1108 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
1109 final String vfResourceName,
1110 final CsarInfo csarInfo) {
1111 final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
1113 final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
1114 if (!nodes.isEmpty()) {
1115 final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
1116 while (nodesNameEntry.hasNext()) {
1117 final Entry<String, Object> nodeType = nodesNameEntry.next();
1118 final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
1119 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
1120 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
1123 for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
1124 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
1125 vfResourceName, cvfc.getType()));
1127 return vfcToscaNames;
1130 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1131 Map<String, Object> nodes = new HashMap<>();
1132 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
1133 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
1135 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
1139 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
1140 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1141 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
1142 if (eitherNodeTypes.isLeft()) {
1143 nodes.putAll(eitherNodeTypes.left()
1148 public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
1150 log.trace("************* created successfully from YAML, resource TOSCA ");
1151 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
1152 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
1153 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
1154 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
1155 nodeTypesInfo, csarInfo, resource);
1156 if (findNodeTypesArtifactsToHandleRes.isRight()) {
1157 log.debug("failed to find node types for update with artifacts during import csar {}. ",
1158 csarInfo.getCsarUUID());
1159 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1160 StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
1161 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
1163 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
1164 csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
1167 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
1168 vfResource.getToscaResourceName());
1169 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
1173 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1174 log.trace("validating resource before create");
1175 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
1176 // validate user role
1177 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
1178 // VF / PNF "derivedFrom" should be null (or ignored)
1179 if (ModelConverter.isAtomicComponent(resource)) {
1180 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1182 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1186 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
1187 // nodeTypesArtifactsToCreate, true, false, null
1188 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1189 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1190 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1191 boolean shouldLock, boolean inTransaction, String nodeName) {
1193 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
1194 Resource createdResource;
1196 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
1197 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
1198 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
1200 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
1201 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1202 StatusCode.STARTED,"");
1203 createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1204 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
1205 csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1206 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
1207 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
1208 StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
1209 } catch (ComponentException e) {
1210 ResponseFormat responseFormat = e.getResponseFormat() == null
1211 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
1212 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1213 AuditingActionEnum.IMPORT_RESOURCE);
1215 } catch (StorageException e) {
1216 ResponseFormat responseFormat = componentsUtils
1217 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1218 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
1219 AuditingActionEnum.IMPORT_RESOURCE);
1222 return createdResource;
1226 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
1227 Map<String, Object> mappedToscaTemplate, boolean needLock,
1228 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1229 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1230 CsarInfo csarInfo) {
1232 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1233 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1234 if (toscaVersion.isRight()) {
1235 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1237 Map<String, Object> mapToConvert = new HashMap<>();
1238 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
1240 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1241 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1242 nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1243 return csarInfo.getCreatedNodes();
1246 private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1247 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1249 .orValue(HashMap::new);
1252 private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
1253 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1254 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1255 CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1256 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
1258 Resource vfcCreated = null;
1259 while (nodesNameValueIter.hasNext()) {
1260 Entry<String, Object> nodeType = nodesNameValueIter.next();
1261 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1262 || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1264 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1265 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1266 vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1267 nodeTypesInfo, csarInfo, nodeType.getKey());
1268 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1269 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1270 && !csarInfo.getCreatedNodesToscaResourceNames()
1271 .containsKey(nodeType.getKey())) {
1272 log.trace("************* Going to create node {}", nodeType.getKey());
1273 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
1274 nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
1275 nodeTypesNewCreatedArtifacts, true, csarInfo, true);
1276 log.debug("************* Finished to create node {}", nodeType.getKey());
1278 vfcCreated = resourceCreated.getLeft();
1279 csarInfo.getCreatedNodesToscaResourceNames()
1280 .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
1282 if (vfcCreated != null) {
1283 csarInfo.getCreatedNodes()
1284 .put(nodeType.getKey(), vfcCreated);
1286 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1290 private Resource handleNestedVfc(Resource resource,
1291 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1292 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1295 String yamlName = nodesInfo.get(nodeName)
1296 .getTemplateFileName();
1297 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
1298 .getMappedToscaTemplate();
1300 log.debug("************* Going to create node types from yaml {}", yamlName);
1301 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
1302 createdArtifacts, Collections.emptyMap(), csarInfo);
1303 log.debug("************* Finished to create node types from yaml {}", yamlName);
1305 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1306 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1307 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
1308 nodeName, yamlName);
1313 private Resource handleComplexVfc(final Resource resource,
1314 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
1315 nodesArtifactsToHandle,
1316 final List<ArtifactDefinition>
1317 createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1318 final String nodeName, final String yamlName) {
1320 Resource oldComplexVfc = null;
1321 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1322 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1323 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1324 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1325 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1326 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
1328 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1329 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1330 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1331 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1332 } else if (oldComplexVfcRes.isLeft()) {
1333 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1334 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1335 oldComplexVfcRes.left().value(),
1336 newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1337 if (eitherValidation.isLeft()) {
1338 oldComplexVfc = oldComplexVfcRes.left().value();
1341 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
1342 yamlName, oldComplexVfc, newComplexVfc);
1343 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1344 final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1345 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1346 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1347 final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
1348 lifecycleChangeInfo, true, false, true);
1349 csarInfo.getCreatedNodes().put(nodeName, result);
1350 csarInfo.removeNodeFromQueue();
1354 private Resource handleComplexVfc(
1355 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1356 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1357 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1359 Resource handleComplexVfcRes;
1360 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
1361 .getMappedToscaTemplate();
1362 String yamlContent = new String(csarInfo.getCsar()
1364 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
1366 .collect(toMap(Entry::getKey, e -> e.getValue()
1367 .getUnmarkedCopy()));
1368 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1369 if (oldComplexVfc == null) {
1370 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1371 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1373 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1374 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1375 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1377 return handleComplexVfcRes;
1380 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1381 Map<String, NodeTypeInfo> nodesInfo) {
1383 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1384 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1385 csarInfo.addNodeToQueue(nodeName);
1386 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
1390 private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
1392 final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
1393 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1395 if(findTypes.length > 1){
1396 final String resourceType = findTypes[0];
1397 return nameWithouNamespacePrefix.substring(resourceType.length());
1399 return nameWithouNamespacePrefix;
1402 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
1403 final Entry<String, Object> nodeNameValue,
1405 final Map<String, Object> mapToConvert,
1406 final Resource resourceVf,
1407 final boolean needLock,
1408 final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1409 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1410 final boolean forceCertificationAllowed,
1411 final CsarInfo csarInfo,
1412 final boolean isNested) {
1414 final UploadResourceInfo resourceMetaData = fillResourceMetadata(
1415 yamlName, resourceVf, nodeNameValue.getKey(), user);
1417 final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
1418 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1419 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1420 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1421 nodeNameValue.getKey(), isNested);
1424 private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
1425 final Map<String, Object> mapToConvert,
1426 final String nodeResourceType,
1427 final CsarInfo csarInfo) {
1428 // We need to create a Yaml from each node_types in order to create
1429 // resource from each node type using import normative flow.
1430 final DumperOptions options = new DumperOptions();
1431 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1432 final Yaml yaml = new Yaml(options);
1434 final Map<String, Object> node = new HashMap<>();
1435 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1436 .getLeft(), nodeNameValue.getValue());
1437 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1439 return yaml.dumpAsMap(mapToConvert);
1442 public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
1443 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1447 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
1448 UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1449 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1450 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1451 String nodeName, boolean isNested) {
1453 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1454 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1455 Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
1457 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1458 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1459 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1463 * Validates if a given node type name has a valid prefix.
1465 * @param nodeName node name from definition file
1466 * @param definedResourceNamespaceList is a list of all node type name prefix allowed
1467 * @return a valid node type name prefix if it`s found
1469 public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
1470 final List<String> definedResourceNamespaceList) {
1471 for (final String validNamespace : definedResourceNamespaceList) {
1472 if (nodeName.startsWith(validNamespace)) {
1473 return Optional.of(validNamespace);
1476 return Optional.empty();
1479 private List<String> getDefinedNodeTypeNamespaceList() {
1480 return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
1483 private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
1484 final String nodeName, final User user) {
1486 final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1488 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
1489 log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
1491 if (!nodeName.startsWith(nodeTypeNamePrefix)) {
1492 log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
1493 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1494 resourceMetaData.getName(), nodeName);
1497 final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
1498 final String namePrefix = nodeName.replace(actualName, "");
1499 String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
1500 log.debug("initial namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
1501 resourceType, nodeName, actualName, nodeTypeNamePrefix);
1503 // if we import from csar, the node_type name can be
1504 // org.openecomp.resource.abstract.node_name - in this case we always
1506 if (resourceType.equals(Constants.ABSTRACT)) {
1507 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1510 if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
1511 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1515 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1516 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
1517 resourceType.toUpperCase(), ResourceTypeEnum.values());
1518 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
1519 resourceMetaData.getName(), nodeName);
1523 resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
1525 // Setting type from name
1526 final String type = resourceType.toUpperCase();
1527 resourceMetaData.setResourceType(type);
1529 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1530 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1531 resourceMetaData.setContactId(user.getUserId());
1532 resourceMetaData.setVendorName(resourceVf.getVendorName());
1533 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1536 final List<String> tags = new ArrayList<>();
1537 tags.add(resourceMetaData.getName());
1538 resourceMetaData.setTags(tags);
1541 final CategoryDefinition category = new CategoryDefinition();
1542 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1543 final SubCategoryDefinition subCategory = new SubCategoryDefinition();
1544 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1545 category.addSubCategory(subCategory);
1546 final List<CategoryDefinition> categories = new ArrayList<>();
1547 categories.add(category);
1548 resourceMetaData.setCategories(categories);
1550 return resourceMetaData;
1553 private Resource buildComplexVfcMetadata(final Resource resourceVf,
1554 final CsarInfo csarInfo,
1555 final String nodeName,
1556 final Map<String, NodeTypeInfo> nodesInfo) {
1557 final Resource cvfc = new Resource();
1558 final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1559 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1560 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1561 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1562 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1563 cvfc.setAbstract(true);
1564 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1565 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1566 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1567 cvfc.setContactId(csarInfo.getModifier()
1569 cvfc.setCreatorUserId(csarInfo.getModifier()
1571 cvfc.setVendorName(resourceVf.getVendorName());
1572 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1573 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1574 cvfc.setToscaResourceName(buildNestedToscaResourceName(
1575 ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
1576 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1578 final List<String> tags = new ArrayList<>();
1579 tags.add(cvfc.getName());
1582 final CategoryDefinition category = new CategoryDefinition();
1583 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1584 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1585 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1586 category.addSubCategory(subCategory);
1587 final List<CategoryDefinition> categories = new ArrayList<>();
1588 categories.add(category);
1589 cvfc.setCategories(categories);
1591 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1592 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1593 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1598 private String buildCvfcName(final String resourceVfName, final String nodeName) {
1600 String nameWithouNamespacePrefix =
1601 nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1602 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1603 String resourceType = findTypes[0];
1604 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1605 return addCvfcSuffixToResourceName(resourceName);
1608 private Resource createResourceAndRIsFromYaml(final String yamlName,
1610 final ParsedToscaYamlInfo parsedToscaYamlInfo,
1611 final AuditingActionEnum actionEnum,
1612 final boolean isNormative,
1613 final List<ArtifactDefinition> createdArtifacts,
1614 final String topologyTemplateYaml,
1615 final Map<String, NodeTypeInfo> nodeTypesInfo,
1616 final CsarInfo csarInfo,
1617 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1618 final boolean shouldLock,
1619 final boolean inTransaction,
1620 final String nodeName) {
1622 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1625 final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1627 if (lockResult.isRight()) {
1628 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1629 throw new ByResponseFormatComponentException(lockResult.right().value());
1631 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1634 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1635 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
1636 final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1637 resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
1638 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1639 log.trace("************* Going to add inputs from yaml {}", yamlName);
1640 if (resource.shouldGenerateInputs())
1641 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1643 final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1644 resource = createInputsOnResource(resource, inputs);
1645 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1646 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
1647 resource.getComponentMetadataForSupportLog(),
1648 StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
1649 if (resource.getResourceType() == ResourceTypeEnum.PNF) {
1650 log.trace("************* Adding generic properties to PNF");
1651 resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
1652 genericResource.getProperties());
1653 log.trace("************* Adding software information to PNF");
1654 softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
1655 log.trace("************* Removing non-mano software information file from PNF");
1656 if (csarInfo.getSoftwareInformationPath().isPresent() &&
1657 !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
1658 log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
1659 "catalog-be", "Could not remove the software information file.");
1663 final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1665 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1666 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations from yaml: {}",yamlName);
1667 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1668 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
1670 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1671 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
1672 resource.getComponentMetadataForSupportLog(),
1673 StatusCode.COMPLETE,"Finished to create nodes, RI and Relation from yaml: {}",yamlName);
1674 // validate update vf module group names
1675 final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1676 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1677 if (validateUpdateVfGroupNamesRes.isRight()) {
1678 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1679 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1681 // add groups to resource
1682 final Map<String, GroupDefinition> groups;
1683 log.trace("************* Going to add groups from yaml {}", yamlName);
1684 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
1685 StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
1686 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1687 groups = validateUpdateVfGroupNamesRes.left().value();
1689 groups = parsedToscaYamlInfo.getGroups();
1692 final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
1693 if (createGroupsOnResource.isRight()) {
1694 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1695 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1696 resource.getComponentMetadataForSupportLog(),
1697 StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
1698 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1700 resource = createGroupsOnResource.left().value();
1701 log.trace("************* Finished to add groups from yaml {}", yamlName);
1702 loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
1703 resource.getComponentMetadataForSupportLog(),
1704 StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
1705 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1706 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1707 resource.getComponentMetadataForSupportLog(),
1708 StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
1710 log.trace("************* Starting to add policies from yaml {}", yamlName);
1711 Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
1712 if (MapUtils.isNotEmpty(policies)) {
1713 resource = createPoliciesOnResource(resource, policies);
1715 log.trace("************* Finished to add policies from yaml {}", yamlName);
1717 final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
1718 new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
1720 final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
1721 ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
1722 nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1723 if (createArtifactsEither.isRight()) {
1724 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1725 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1726 resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
1727 createArtifactsEither.right().value());
1728 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1730 loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
1731 resource.getComponentMetadataForSupportLog(),
1732 StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
1733 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1734 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1735 ASDCKpiApi.countCreatedResourcesKPI();
1738 } catch (final ComponentException | StorageException e) {
1739 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1741 } catch (final ToscaOperationException e) {
1742 log.error("An error has occurred during resource and resource instance creation", e);
1743 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1744 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
1745 "catalog-be", e.getMessage());
1746 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1747 } catch (final BusinessLogicException e) {
1748 log.error("An error has occurred during resource and resource instance creation", e);
1749 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1750 throw new ByResponseFormatComponentException(e.getResponseFormat());
1752 if (!inTransaction) {
1753 janusGraphDao.commit();
1756 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1757 NodeTypeEnum.Resource);
1762 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
1763 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1764 if (!inTransaction) {
1765 janusGraphDao.rollback();
1767 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1768 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1769 log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
1770 resource.getName());
1774 private Resource getResourceWithGroups(String resourceId) {
1776 ComponentParametersView filter = new ComponentParametersView();
1777 filter.setIgnoreGroups(false);
1778 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
1780 if (updatedResource.isRight()) {
1781 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
1782 .value()), resourceId);
1784 return updatedResource.left()
1788 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1789 Map<String, GroupDefinition> groups) {
1790 if (groups != null && !groups.isEmpty()) {
1791 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1792 handleGroupsProperties(resource, groups);
1793 fillGroupsFinalFields(groupsAsList);
1794 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1795 groupsAsList, true);
1796 if (createGroups.isRight()) {
1797 return Either.right(createGroups.right()
1801 return Either.left(resource);
1804 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1805 List<InputDefinition> inputs = resource.getInputs();
1806 if (MapUtils.isNotEmpty(groups)) {
1809 .filter(g -> isNotEmpty(g.getProperties()))
1810 .flatMap(g -> g.getProperties()
1812 .forEach(p -> handleGetInputs(p, inputs));
1816 private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
1817 policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
1821 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1822 if (isNotEmpty(property.getGetInputValues())) {
1823 if (inputs == null || inputs.isEmpty()) {
1824 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1825 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1827 .map(GetInputValueDataDefinition::getInputName)
1831 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
1833 while (getInputValuesIter.hasNext()) {
1834 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1835 Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
1836 if (inputEither.isRight()) {
1837 throw inputEither.right().value();
1839 InputDefinition input = inputEither.left().value();
1840 getInput.setInputId(input.getUniqueId());
1841 if (getInput.getGetInputIndex() != null) {
1842 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1843 Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
1845 if (newInputEither.isRight()) {
1846 throw newInputEither.right().value();
1848 InputDefinition newInput = newInputEither.left().value();
1849 getInputIndex.setInputId(newInput.getUniqueId());
1851 getInputValuesIter.add(getInputIndex);
1858 static <T> Either<T, RuntimeException> rollbackWithEither(
1859 final JanusGraphDao janusGraphDao,
1860 final ActionStatus actionStatus,
1861 final String... params) {
1862 if (janusGraphDao != null)
1863 janusGraphDao.rollback();
1864 return Either.right(new ByActionStatusComponentException(actionStatus, params));
1867 <T> Either<T, RuntimeException> rollbackWithEither(
1868 final ActionStatus actionStatus,
1869 final String... params) {
1870 return rollbackWithEither(janusGraphDao, actionStatus, params);
1873 private Either<InputDefinition, RuntimeException> findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1875 final String inputName = getInput != null ? getInput.getInputName() : "";
1877 if(inputs == null || inputs.isEmpty()) {
1878 log.debug("#findInputByName - Inputs list is empty");
1879 return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
1881 Optional<InputDefinition> inputOpt = inputs.stream()
1882 .filter(p -> p.getName().equals(inputName))
1884 if (!inputOpt.isPresent()) {
1885 log.debug("#findInputByName - Failed to find the input {} ", inputName);
1886 return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
1888 return Either.left(inputOpt.get());
1893 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1894 groupsAsList.forEach(groupDefinition -> {
1895 groupDefinition.setInvariantName(groupDefinition.getName());
1896 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1900 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1901 if (isEmpty(groups)) {
1904 return updateOrCreateGroups(resource, groups);
1907 private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1908 List<GroupDefinition> groupsFromResource = resource.getGroups();
1909 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1910 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1911 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1912 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1913 if (isNotEmpty(groupsFromResource)) {
1914 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1915 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1917 groupsToCreate.addAll(groupsAsList);
1919 if (isNotEmpty(groupsToCreate)) {
1920 fillGroupsFinalFields(groupsToCreate);
1921 if (isNotEmpty(groupsFromResource)) {
1922 groupBusinessLogic.addGroups(resource, groupsToCreate, true)
1924 .on(this::throwComponentException);
1926 groupBusinessLogic.createGroups(resource, groupsToCreate, true)
1928 .on(this::throwComponentException);
1931 if (isNotEmpty(groupsToDelete)) {
1932 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1934 .on(this::throwComponentException);
1936 if (isNotEmpty(groupsToUpdate)) {
1937 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1939 .on(this::throwComponentException);
1945 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1946 List<GroupDefinition> groupsToDelete) {
1947 for (GroupDefinition group : groupsFromResource) {
1948 Optional<GroupDefinition> op = groupsAsList.stream()
1949 .filter(p -> p.getInvariantName()
1950 .equalsIgnoreCase(group.getInvariantName()))
1952 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
1954 groupsToDelete.add(group);
1959 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
1960 List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1961 for (GroupDefinition group : groupsAsList) {
1962 Optional<GroupDefinition> op = groupsFromResource.stream()
1963 .filter(p -> p.getInvariantName()
1964 .equalsIgnoreCase(group.getInvariantName()))
1966 if (op.isPresent()) {
1967 GroupDefinition groupToUpdate = op.get();
1968 groupToUpdate.setMembers(group.getMembers());
1969 groupToUpdate.setCapabilities(group.getCapabilities());
1970 groupToUpdate.setProperties(group.getProperties());
1971 groupsToUpdate.add(groupToUpdate);
1973 groupsToCreate.add(group);
1978 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1979 List<InputDefinition> resourceProperties = resource.getInputs();
1980 if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
1982 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1984 if (createInputs.isRight()) {
1985 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
1986 StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
1988 throw new ByResponseFormatComponentException(createInputs.right()
1991 resource.setInputs(createInputs.left().value());
1996 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
1997 Resource component) {
1999 List<GroupDefinition> result = new ArrayList<>();
2000 List<ComponentInstance> componentInstances = component.getComponentInstances();
2002 if (groups != null) {
2003 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
2004 if (validateCyclicGroupsDependencies.isRight()) {
2005 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
2007 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
2008 String groupName = entry.getKey();
2009 GroupDefinition groupDefinition = entry.getValue();
2010 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2011 updatedGroupDefinition.setMembers(null);
2012 Map<String, String> members = groupDefinition.getMembers();
2013 if (members != null) {
2014 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
2017 result.add(updatedGroupDefinition);
2023 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
2024 Resource component, List<ComponentInstance> componentInstances, String groupName,
2025 Map<String, String> members) {
2026 Set<String> compInstancesNames = members.keySet();
2028 if (CollectionUtils.isEmpty(componentInstances)) {
2029 String membersAstString = compInstancesNames.stream()
2030 .collect(joining(","));
2032 "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
2033 membersAstString, groupName, component.getNormalizedName());
2034 throw new ByActionStatusComponentException(
2035 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2036 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2038 // Find all component instances with the member names
2039 Map<String, String> memberNames = componentInstances.stream()
2040 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2041 memberNames.putAll(groups.keySet()
2043 .collect(toMap(g -> g, g -> "")));
2044 Map<String, String> relevantInstances = memberNames.entrySet()
2046 .filter(n -> compInstancesNames.contains(n.getKey()))
2047 .collect(toMap(Entry::getKey, Entry::getValue));
2049 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2051 List<String> foundMembers = new ArrayList<>();
2052 if (relevantInstances != null) {
2053 foundMembers = relevantInstances.keySet()
2057 compInstancesNames.removeAll(foundMembers);
2058 String membersAstString = compInstancesNames.stream()
2059 .collect(joining(","));
2060 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
2061 component.getNormalizedName());
2062 throw new ByActionStatusComponentException(
2063 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
2064 groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
2066 updatedGroupDefinition.setMembers(relevantInstances);
2070 * This Method validates that there is no cyclic group dependencies. meaning
2071 * group A as member in group B which is member in group A
2076 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
2078 Either<Boolean, ResponseFormat> result = Either.left(true);
2080 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
2082 while (allGroupsItr.hasNext() && result.isLeft()) {
2083 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
2084 // Fetches a group member A
2085 String groupAName = groupAEntry.getKey();
2086 // Finds all group members in group A
2087 Set<String> allGroupAMembersNames = new HashSet<>();
2088 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
2089 // If A is a group member of itself found cyclic dependency
2090 if (allGroupAMembersNames.contains(groupAName)) {
2091 ResponseFormat responseFormat = componentsUtils
2092 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
2093 result = Either.right(responseFormat);
2096 } catch (Exception e) {
2097 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2098 result = Either.right(responseFormat);
2099 log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
2105 * This Method fills recursively the set groupMembers with all the members
2106 * of the given group which are also of type group.
2110 * @param allGroupMembers
2113 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
2114 Set<String> allGroupMembers) {
2116 // Found Cyclic dependency
2117 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
2120 GroupDefinition groupDefinition = allGroups.get(groupName);
2121 // All Members Of Current Group Resource Instances & Other Groups
2122 Set<String> currGroupMembers = groupDefinition.getMembers()
2124 // Filtered Members Of Current Group containing only members which
2126 List<String> currGroupFilteredMembers = currGroupMembers.stream()
2128 // Keep Only Elements of type group and not Resource Instances
2129 filter(allGroups::containsKey)
2131 // Add Filtered Elements to main Set
2132 peek(allGroupMembers::add)
2137 // Recursively call the method for all the filtered group members
2138 for (String innerGroupName : currGroupFilteredMembers) {
2139 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
2144 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
2145 Set<String> allGroupMembers) {
2147 boolean stop = false;
2148 // In Case Not Group Stop
2149 if (!allGroups.containsKey(groupName)) {
2152 // In Case Group Has no members stop
2154 GroupDefinition groupDefinition = allGroups.get(groupName);
2155 stop = isEmpty(groupDefinition.getMembers());
2158 // In Case all group members already contained stop
2160 final Set<String> allMembers = allGroups.get(groupName)
2163 Set<String> membersOfTypeGroup = allMembers.stream()
2165 // Filter In Only Group members
2166 filter(allGroups::containsKey)
2170 stop = allGroupMembers.containsAll(membersOfTypeGroup);
2175 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
2176 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
2177 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2179 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2182 log.debug("************* Going to create all nodes {}", yamlName);
2183 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
2184 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
2185 log.debug("************* Finished to create all nodes {}", yamlName);
2186 log.debug("************* Going to create all resource instances {}", yamlName);
2187 Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
2188 resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
2189 csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
2190 log.debug("************* Finished to create all resource instances {}", yamlName);
2191 log.debug("************* Going to create all relations {}", yamlName);
2192 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
2193 log.debug("************* Finished to create all relations {}", yamlName);
2194 log.debug("************* Going to create positions {}", yamlName);
2195 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
2197 log.debug("************* Finished to set positions {}", yamlName);
2201 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
2202 List<ArtifactDefinition> artifactsToAdd) {
2203 List<String> vfcArtifactNames = vfcArtifacts.stream()
2204 .map(ArtifactDataDefinition::getArtifactName)
2206 artifactsToAdd.stream()
2208 if (!vfcArtifactNames.contains(a.getArtifactName())) {
2209 vfcArtifacts.add(a);
2211 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
2217 @SuppressWarnings("unchecked")
2218 private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
2219 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2220 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2221 CsarInfo csarInfo, String nodeName) {
2223 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2224 if (nodeTypeEntry.getValue()
2227 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
2228 csarInfo, nodeTypeEntry.getKey());
2229 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2232 Map<String, Object> mappedToscaTemplate = null;
2233 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
2234 mappedToscaTemplate = nodeTypesInfo.get(nodeName)
2235 .getMappedToscaTemplate();
2237 if (isEmpty(mappedToscaTemplate)) {
2238 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2240 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
2241 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2242 } catch (ComponentException e) {
2243 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
2244 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
2245 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2246 AuditingActionEnum.IMPORT_RESOURCE);
2248 } catch (StorageException e) {
2249 ResponseFormat responseFormat = componentsUtils
2250 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
2251 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
2252 AuditingActionEnum.IMPORT_RESOURCE);
2257 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
2258 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
2259 boolean inTransaction) {
2261 if (csarInfo.getCsar() != null) {
2262 String vendorLicenseModelId = null;
2263 String vfLicenseModelId = null;
2265 if (artifactOperation.isUpdate()) {
2266 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
2267 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
2268 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
2269 if (artifactEntry.getValue()
2271 .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
2272 vendorLicenseModelId = artifactEntry.getValue()
2275 if (artifactEntry.getValue()
2277 .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
2278 vfLicenseModelId = artifactEntry.getValue()
2285 // Specific Behavior for license artifacts
2286 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2287 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
2288 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
2289 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
2290 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
2291 shouldLock, inTransaction);
2292 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2293 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
2294 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
2295 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
2296 artifactOperation, null, true, shouldLock, inTransaction);
2298 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
2299 createdArtifacts, shouldLock, inTransaction, artifactOperation);
2300 if (eitherCreateResult.isRight()) {
2301 return Either.right(eitherCreateResult.right()
2305 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
2306 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
2308 if (artifacsMetaCsarStatus.isLeft()) {
2309 String artifactsFileName = artifacsMetaCsarStatus.left()
2312 String artifactsContents = artifacsMetaCsarStatus.left()
2315 Either<Resource, ResponseFormat> createArtifactsFromCsar;
2316 if (artifactOperation.isCreateOrLink()) {
2317 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
2318 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
2320 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
2321 csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
2323 if ((result.left().value() instanceof Resource) && result.isLeft()) {
2324 Resource service1 = (Resource) result.left().value();
2325 createArtifactsFromCsar = Either.left(service1);
2327 createArtifactsFromCsar = Either.right(result.right().value());
2331 if (createArtifactsFromCsar.isRight()) {
2332 log.debug("Couldn't create artifacts from artifacts.meta");
2333 return Either.right(createArtifactsFromCsar.right()
2337 return Either.left(createArtifactsFromCsar.left()
2341 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
2346 return Either.left(resource);
2349 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
2350 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
2351 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
2352 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
2353 boolean shouldLock, boolean inTransaction) {
2354 byte[] artifactFileBytes = null;
2356 if (csarInfo.getCsar()
2357 .containsKey(artifactPath)) {
2358 artifactFileBytes = csarInfo.getCsar()
2361 Either<Boolean, ResponseFormat> result = Either.left(true);
2362 if (operation.isUpdate() || operation.isDelete()) {
2363 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
2364 Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
2365 .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
2366 resource, shouldLock,
2368 if (handleDelete.isRight()) {
2369 result = Either.right(handleDelete.right()
2372 ArtifactDefinition value = handleDelete.left().value();
2373 String updatedArtifactId = value.getUniqueId();
2374 if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2375 resource.getDeploymentArtifacts().remove(updatedArtifactId);
2377 resource.getArtifacts().remove(updatedArtifactId);
2383 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2384 operation = new ArtifactOperationInfo(false, false,
2385 ArtifactOperationEnum.CREATE);
2389 if (artifactFileBytes != null) {
2390 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
2391 artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
2392 artifactDescription, artifactFileBytes, null, isFromCsar);
2393 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
2394 .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
2396 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2397 if (eitherNonMetaArtifacts.isRight()) {
2398 BeEcompErrorManager.getInstance()
2399 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2400 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2401 ErrorSeverity.WARNING);
2402 return Either.right(eitherNonMetaArtifacts.right()
2405 ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
2406 createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
2412 private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
2413 if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
2414 resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
2416 resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
2420 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2421 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2424 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2425 List<ArtifactDefinition> createdArtifacts,
2426 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2427 if (operation.isCreateOrLink() && createdArtifacts != null
2428 && eitherNonMetaArtifacts.isLeft()) {
2429 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
2431 if (eitherResult.isLeft()) {
2432 createdArtifacts.add(eitherResult.left()
2438 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2439 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2440 ArtifactOperationInfo artifactOperation) {
2442 Either<Resource, ResponseFormat> resStatus = null;
2443 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2446 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
2447 collectedWarningMessages);
2448 if (artifactPathAndNameList.isRight()) {
2449 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2450 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
2453 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2455 if (artifactOperation.isCreateOrLink()) {
2456 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2457 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
2460 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2461 resource, artifactPathAndNameList.left()
2463 csarInfo.getModifier());
2465 if (findVfCsarArtifactsToHandleRes.isRight()) {
2466 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
2469 if (resStatus == null) {
2470 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
2474 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2475 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
2476 resStatus, vfCsarArtifactsToHandle);
2478 if (resStatus == null) {
2479 resStatus = Either.left(resource);
2481 } catch (Exception e) {
2482 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2483 log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2485 CsarUtils.handleWarningMessages(collectedWarningMessages);
2490 private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
2491 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2492 Either<Resource, ResponseFormat> resStatus,
2493 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2494 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2497 Optional<ResponseFormat> optionalCreateInDBError =
2498 // Stream of artifacts to be created
2499 currArtifactOperationPair.getValue()
2501 // create each artifact
2502 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2503 e.getArtifactName(), e.getArtifactType(),
2504 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2505 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2506 new ArtifactOperationInfo(false, false,
2507 currArtifactOperationPair.getKey()),
2508 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2509 // filter in only error
2510 .filter(Either::isRight)
2512 // Convert the error from either to
2517 // Check if an error occurred
2519 // Error found on artifact Creation
2520 if (optionalCreateInDBError.isPresent()) {
2521 resStatus = Either.right(optionalCreateInDBError.get());
2528 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
2529 Map<String, Set<List<String>>> collectedWarningMessages) {
2530 List<NonMetaArtifactInfo> artifactPathAndNameList =
2531 // Stream of file paths contained in csar
2535 // Filter in only VF artifact path location
2536 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
2537 .matcher(e.getKey())
2539 // Validate and add warnings
2540 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2541 // Filter in Non Warnings
2542 .filter(Either::isLeft)
2543 // Convert from Either to NonMetaArtifactInfo
2548 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2549 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2550 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
2552 return Either.right(nonMetaArtifactInfo.getArtifactName());
2555 return Either.left(artifactPathAndNameList);
2558 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2559 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2561 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2562 // collect all Deployment and Informational artifacts of VF
2563 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
2565 existingArtifacts.addAll(resource.getDeploymentArtifacts()
2568 if (resource.getArtifacts() != null && !resource.getArtifacts()
2570 existingArtifacts.addAll(resource.getArtifacts()
2573 existingArtifacts = existingArtifacts.stream()
2574 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2575 // was created from HEAT.meta
2576 .filter(this::isNonMetaArtifact)
2579 List<String> artifactsToIgnore = new ArrayList<>();
2580 // collect IDs of Artifacts of VF which belongs to any group
2581 if (resource.getGroups() != null) {
2582 resource.getGroups()
2585 if (g.getArtifacts() != null && !g.getArtifacts()
2587 artifactsToIgnore.addAll(g.getArtifacts());
2591 existingArtifacts = existingArtifacts.stream()
2592 // filter artifacts which belongs to any group
2593 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
2595 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2598 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2599 boolean result = true;
2600 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2606 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2607 boolean result = true;
2608 if (artifact.getArtifactType() == null
2609 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2610 || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2616 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
2617 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
2618 log.debug("#createResourceInstancesRelations - Going to create relations ");
2619 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start to create relations");
2620 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2621 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
2622 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
2624 "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
2625 resource.getUniqueId(), yamlName);
2626 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
2627 BeEcompErrorManager.getInstance()
2628 .logInternalDataError("createResourceInstancesRelations",
2629 "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2630 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2632 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2633 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2634 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2635 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2636 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2637 Map<String, List<AttributeDataDefinition>> instAttributes = new HashMap<>();
2638 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2639 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2641 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2642 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2643 if (allDataTypes.isRight()) {
2644 JanusGraphOperationStatus status = allDataTypes.right()
2646 BeEcompErrorManager.getInstance()
2647 .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2648 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2649 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2650 StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
2651 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2652 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
2655 Resource finalResource = resource;
2656 uploadResInstancesMap.values()
2657 .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2658 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
2659 instAttributes, existingNodeTypesByResourceNames, instInputs, i));
2660 resource.getComponentInstances()
2662 .filter(i -> !i.isCreatedFromCsar())
2663 .forEach(i->processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
2665 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2666 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2667 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2668 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2669 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2670 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2671 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2672 associateResourceInstances(yamlName, resource, relations);
2673 handleSubstitutionMappings(resource, uploadResInstancesMap);
2674 log.debug("************* in create relations, getResource start");
2675 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"create relations");
2676 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2677 .getToscaFullElement(resource.getUniqueId());
2678 log.debug("************* in create relations, getResource end");
2679 if (eitherGetResource.isRight()) {
2680 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2681 StatusCode.ERROR,"ERROR while create relations");
2682 throw new ByResponseFormatComponentException(componentsUtils
2683 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
2684 .value()), resource));
2686 return eitherGetResource.left()
2690 private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
2691 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2692 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2693 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2694 Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String,
2695 List<ComponentInstanceProperty>> instProperties, Map<String,
2696 List<ComponentInstanceInput>> instInputs,
2697 Map<String, List<AttributeDataDefinition>> instAttributes) {
2698 Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
2699 if (foundInstance.isPresent()) {
2700 if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) {
2701 instCapabilities.put(instance, foundInstance.get().getCapabilities());
2703 if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) {
2704 instRequirements.put(instance, foundInstance.get().getRequirements());
2706 if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) {
2707 instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
2709 if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
2710 instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
2712 if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
2714 .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
2715 instProperties.put(instance.getUniqueId(),
2716 oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
2718 if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
2720 .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
2721 instInputs.put(instance.getUniqueId(),
2722 oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
2724 if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
2725 CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
2726 instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new).collect(toList()));
2731 private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
2732 if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
2733 return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
2735 return Optional.empty();
2738 private void associateResourceInstances(String yamlName, Resource resource,
2739 List<RequirementCapabilityRelDef> relations) {
2740 Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
2742 if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
2743 StorageOperationStatus status = relationsEither.right().value();
2744 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2746 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
2748 setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
2752 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
2753 Map<String, List<AttributeDataDefinition>> instAttributes) {
2754 StorageOperationStatus addArtToInst;
2755 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2757 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2758 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2760 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst),
2765 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
2766 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
2767 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2768 StorageOperationStatus addArtToInst;
2769 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2771 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2772 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2774 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2778 private void associateArtifactsToInstances(String yamlName, Resource resource,
2779 Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2780 StorageOperationStatus addArtToInst;
2782 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
2783 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2784 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2785 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2789 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
2790 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2791 StorageOperationStatus addArtToInst = toscaOperationFacade
2792 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
2793 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2794 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2795 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2799 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
2800 Map<String, List<ComponentInstanceInput>> instInputs) {
2801 if (MapUtils.isNotEmpty(instInputs)) {
2802 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2803 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2804 if (addInputToInst.isRight()) {
2806 StorageOperationStatus addInputToInstError = addInputToInst.right().value();
2807 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2808 addInputToInstError);
2809 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
2811 setComponentInstanceInputsOnComponent(resource, instInputs);
2815 private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2816 Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
2817 if (componentInstancesInputs == null)
2818 componentInstancesInputs = new HashMap<>();
2819 componentInstancesInputs.putAll(instInputs);
2820 resource.setComponentInstancesInputs(componentInstancesInputs);
2823 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
2824 Map<String, List<ComponentInstanceProperty>> instProperties) {
2825 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2826 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2827 if (addPropToInst.isRight()) {
2828 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
2829 StatusCode.ERROR,"ERROR while associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
2830 StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
2831 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2832 storageOperationStatus);
2833 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
2835 setComponentInstancePropertiesOnComponent(resource, instProperties);
2838 private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2839 Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
2840 if (componentInstanceProps == null )
2841 componentInstanceProps = new HashMap<>();
2842 componentInstanceProps.putAll(instProperties);
2843 resource.setComponentInstancesProperties(componentInstanceProps);
2846 private void handleSubstitutionMappings(Resource resource,
2847 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2848 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2849 Either<Resource, StorageOperationStatus> getResourceRes =
2850 updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
2851 if (getResourceRes.isRight()) {
2852 ResponseFormat responseFormat = componentsUtils
2853 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
2854 .value()), resource);
2855 throw new ByResponseFormatComponentException(responseFormat);
2860 private void addRelationsToRI(String yamlName, Resource resource,
2861 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2862 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2863 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2864 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2865 ComponentInstance currentCompInstance = null;
2866 for (ComponentInstance compInstance : componentInstancesList) {
2868 if (compInstance.getName()
2869 .equals(uploadComponentInstanceInfo.getName())) {
2870 currentCompInstance = compInstance;
2875 if (currentCompInstance == null) {
2876 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2877 resource.getUniqueId());
2878 BeEcompErrorManager.getInstance()
2879 .logInternalDataError(
2880 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2881 resource.getUniqueId(), ErrorSeverity.ERROR);
2882 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2885 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2886 if (addRelationToRiRes.getStatus() != 200) {
2887 throw new ByResponseFormatComponentException(addRelationToRiRes);
2893 private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
2894 if (resource.getComponentInstancesRelations() != null) {
2895 resource.getComponentInstancesRelations().addAll(relations);
2897 resource.setComponentInstancesRelations(relations);
2901 private void processComponentInstance(String yamlName, Resource resource,
2902 List<ComponentInstance> componentInstancesList,
2903 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2904 Map<String, List<ComponentInstanceProperty>> instProperties,
2905 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2906 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
2907 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
2908 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
2909 Map<String, List<AttributeDataDefinition>> instAttributes,
2910 Map<String, Resource> originCompMap,
2911 Map<String, List<ComponentInstanceInput>> instInputs,
2912 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2913 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2914 .filter(i -> i.getName()
2915 .equals(uploadComponentInstanceInfo.getName()))
2917 if (!currentCompInstanceOpt.isPresent()) {
2918 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2919 resource.getUniqueId());
2920 BeEcompErrorManager.getInstance()
2921 .logInternalDataError(
2922 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2923 resource.getUniqueId(), ErrorSeverity.ERROR);
2924 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2926 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2927 String resourceInstanceId = currentCompInstance.getUniqueId();
2928 Resource originResource = getOriginResource(originCompMap, currentCompInstance);
2929 if (isNotEmpty(originResource.getRequirements())) {
2930 instRequirements.put(currentCompInstance, originResource.getRequirements());
2932 if (isNotEmpty(originResource.getCapabilities())) {
2933 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2934 currentCompInstance, originResource);
2936 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
2938 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2940 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2941 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2943 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2944 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2946 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2947 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2948 originResource, currentCompInstance, instProperties, allDataTypes.left()
2950 if (addPropertiesValueToRiRes.getStatus() != 200) {
2951 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2954 addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
2960 private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2961 Resource originResource;
2962 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2963 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2964 .getToscaFullElement(currentCompInstance.getComponentUid());
2965 if (getOriginResourceRes.isRight()) {
2966 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2967 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2968 getOriginResourceRes);
2969 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
2970 .value()), currentCompInstance.getComponentUid());
2972 originResource = getOriginResourceRes.left()
2974 originCompMap.put(originResource.getUniqueId(), originResource);
2976 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2978 return originResource;
2981 private void processComponentInstanceCapabilities(
2982 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
2983 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
2984 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2985 Resource originResource) {
2986 Map<String, List<CapabilityDefinition>> originCapabilities;
2987 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2988 originCapabilities = new HashMap<>();
2989 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2990 originResource.getCapabilities()
2991 .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
2992 uploadComponentInstanceInfo.getCapabilities()
2994 .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
2995 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2997 originCapabilities = originResource.getCapabilities();
2999 instCapabilties.put(currentCompInstance, originCapabilities);
3002 private void updateCapabilityPropertiesValues(
3003 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
3004 Map<String, List<CapabilityDefinition>> originCapabilities,
3005 Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
3006 originCapabilities.values()
3008 .flatMap(Collection::stream)
3009 .filter(c -> newPropertiesMap.containsKey(c.getName()))
3010 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
3015 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
3016 List<UploadCapInfo> capabilities) {
3017 for (UploadCapInfo capability : capabilities) {
3018 if (isNotEmpty(capability.getProperties())) {
3019 newPropertiesMap.put(capability.getName(), capability.getProperties()
3021 .collect(toMap(UploadInfo::getName, p -> p)));
3026 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
3027 List<CapabilityDefinition> capabilities) {
3028 List<CapabilityDefinition> list = capabilities.stream()
3029 .map(CapabilityDefinition::new)
3031 originCapabilities.put(type, list);
3034 private void updatePropertyValues(List<ComponentInstanceProperty> properties,
3035 Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
3036 properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
3039 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
3040 Map<String, DataTypeDefinition> allDataTypes) {
3041 String value = null;
3042 List<GetInputValueDataDefinition> getInputs = null;
3043 boolean isValidate = true;
3044 if (null != propertyInfo && propertyInfo.getValue() != null) {
3045 getInputs = propertyInfo.getGet_input();
3046 isValidate = getInputs == null || getInputs.isEmpty();
3048 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
3050 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3051 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3054 property.setValue(value);
3055 return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3058 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
3059 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3060 Either<Resource, StorageOperationStatus> updateRes = null;
3061 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3062 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3063 StorageOperationStatus status = toscaOperationFacade
3064 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
3065 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3067 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
3068 resource.getUniqueId(), status);
3069 updateRes = Either.right(status);
3071 if (updateRes == null) {
3072 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
3073 updatedInstCapabilities, updatedInstRequirements);
3074 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
3075 updatedInstRequirements, resource);
3076 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3078 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
3079 resource.getUniqueId(), status);
3080 updateRes = Either.right(status);
3083 if (updateRes == null) {
3084 updateRes = Either.left(resource);
3089 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
3090 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3091 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
3092 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3094 componentInstances.stream()
3096 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
3097 .getCapabilitiesNamesToUpdate());
3098 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
3099 .getRequirementsNamesToUpdate());
3103 private void fillUpdatedInstRequirements(
3104 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
3105 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3106 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3107 Set<String> updatedReqNames = new HashSet<>();
3108 if (isNotEmpty(requirementsNamesToUpdate)) {
3109 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
3111 updatedRequirements.put(requirements.getKey(), requirements.getValue()
3113 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
3114 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3116 r.setParentName(r.getName());
3117 r.setName(requirementsNamesToUpdate.get(r.getName()));
3118 updatedReqNames.add(r.getName());
3121 .collect(toList()));
3124 if (isNotEmpty(updatedRequirements)) {
3125 updatedInstRequirements.put(instance, updatedRequirements);
3129 private void fillUpdatedInstCapabilities(
3130 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
3131 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3132 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3133 Set<String> updatedCapNames = new HashSet<>();
3134 if (isNotEmpty(capabilitiesNamesToUpdate)) {
3135 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
3137 updatedCapabilities.put(requirements.getKey(), requirements.getValue()
3139 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
3140 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3142 c.setParentName(c.getName());
3143 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
3144 updatedCapNames.add(c.getName());
3147 .collect(toList()));
3150 if (isNotEmpty(updatedCapabilities)) {
3151 updatedInstCapabilties.put(instance, updatedCapabilities);
3155 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
3156 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3157 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3159 ComponentInstance currentCompInstance = null;
3161 for (ComponentInstance compInstance : componentInstancesList) {
3163 if (compInstance.getName()
3164 .equals(nodesInfoValue.getName())) {
3165 currentCompInstance = compInstance;
3171 if (currentCompInstance == null) {
3172 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
3173 BeEcompErrorManager.getInstance()
3174 .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
3175 resource.getUniqueId(), ErrorSeverity.ERROR);
3176 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3178 String resourceInstanceId = currentCompInstance.getUniqueId();
3180 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
3182 if (regMap != null) {
3183 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
3186 while (nodesRegValue.hasNext()) {
3187 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3189 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3190 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3191 log.debug("Going to create relation {}", uploadRegInfo.getName());
3192 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
3193 String regName = uploadRegInfo.getName();
3194 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3195 regCapRelDef.setFromNode(resourceInstanceId);
3196 log.debug("try to find available requirement {} ", regName);
3197 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3198 yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
3199 if (eitherReqStatus.isRight()) {
3200 log.debug("failed to find available requirement {} status is {}", regName,
3201 eitherReqStatus.right()
3203 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
3204 return eitherReqStatus.right()
3208 RequirementDefinition validReq = eitherReqStatus.left()
3210 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3211 .getRelationships();
3212 if (reqAndRelationshipPairList == null) {
3213 reqAndRelationshipPairList = new ArrayList<>();
3215 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3216 reqAndRelationshipPair.setRequirement(regName);
3217 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3218 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3219 RelationshipImpl relationship = new RelationshipImpl();
3220 relationship.setType(validReq.getCapability());
3221 reqAndRelationshipPair.setRelationships(relationship);
3223 ComponentInstance currentCapCompInstance = null;
3224 for (ComponentInstance compInstance : componentInstancesList) {
3225 if (compInstance.getName()
3226 .equals(uploadRegInfo.getNode())) {
3227 currentCapCompInstance = compInstance;
3232 if (currentCapCompInstance == null) {
3233 log.debug("The component instance with name {} not found on resource {} ",
3234 uploadRegInfo.getNode(), resource.getUniqueId());
3235 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
3236 BeEcompErrorManager.getInstance()
3237 .logInternalDataError(
3238 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
3239 resource.getUniqueId(), ErrorSeverity.ERROR);
3240 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3242 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3243 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3244 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3245 currentCapCompInstance, uploadRegInfo);
3247 if (aviableCapForRel == null) {
3248 log.debug("aviable capability was not found. req name is {} component instance is {}",
3249 validReq.getName(), currentCapCompInstance.getUniqueId());
3250 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());
3251 BeEcompErrorManager.getInstance()
3252 .logInternalDataError(
3253 "aviable capability was not found. req name is " + validReq.getName()
3254 + " component instance is " + currentCapCompInstance.getUniqueId(),
3255 resource.getUniqueId(), ErrorSeverity.ERROR);
3256 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3258 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3259 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3260 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3262 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3263 capReqRel.setRelation(reqAndRelationshipPair);
3264 reqAndRelationshipPairList.add(capReqRel);
3265 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3266 relations.add(regCapRelDef);
3269 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3270 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3272 return componentsUtils.getResponseFormat(ActionStatus.OK);
3275 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
3276 Resource originResource, ComponentInstance currentCompInstance,
3277 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3278 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3279 if (MapUtils.isNotEmpty(propMap)) {
3280 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
3281 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3283 if (CollectionUtils.isEmpty(originResource.getInputs())) {
3284 log.debug("failed to find properties ");
3285 loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
3286 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
3288 originResource.getInputs()
3289 .forEach(p -> addInput(currPropertiesMap, p));
3290 for (List<UploadPropInfo> propertyList : propMap.values()) {
3291 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
3294 currPropertiesMap.values()
3295 .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
3296 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3300 private void processProperty(Resource resource, ComponentInstance currentCompInstance,
3301 Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
3302 List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
3303 UploadPropInfo propertyInfo = propertyList.get(0);
3304 String propName = propertyInfo.getName();
3305 if (!currPropertiesMap.containsKey(propName)) {
3306 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3307 StatusCode.ERROR,"ERROR failed to find property: {}",propName);
3308 log.debug("failed to find property {} ", propName);
3309 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
3311 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3312 ComponentInstanceInput property = null;
3314 String value = null;
3315 List<GetInputValueDataDefinition> getInputs = null;
3316 boolean isValidate = true;
3317 if (propertyInfo.getValue() != null) {
3318 getInputs = propertyInfo.getGet_input();
3319 isValidate = getInputs == null || getInputs.isEmpty();
3321 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3323 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3324 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3327 String innerType = null;
3328 property = new ComponentInstanceInput(curPropertyDef, value, null);
3330 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3332 property.setValue(validPropertyVAlue);
3334 if (isNotEmpty(getInputs)) {
3335 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3336 for (GetInputValueDataDefinition getInput : getInputs) {
3337 List<InputDefinition> inputs = resource.getInputs();
3338 if (CollectionUtils.isEmpty(inputs)) {
3339 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3340 StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
3341 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
3342 currentCompInstance.getUniqueId());
3343 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3346 Optional<InputDefinition> optional = inputs.stream()
3347 .filter(p -> p.getName()
3348 .equals(getInput.getInputName()))
3350 if (!optional.isPresent()) {
3351 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3352 StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
3353 log.debug("Failed to find input {} ", getInput.getInputName());
3354 // @@TODO error message
3355 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3357 InputDefinition input = optional.get();
3358 getInput.setInputId(input.getUniqueId());
3359 getInputValues.add(getInput);
3361 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3362 processGetInput(getInputValues, inputs, getInputIndex);
3364 property.setGetInputValues(getInputValues);
3366 instPropList.add(property);
3367 // delete overriden property
3368 currPropertiesMap.remove(property.getName());
3371 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
3372 GetInputValueDataDefinition getInputIndex) {
3373 Optional<InputDefinition> optional;
3374 if (getInputIndex != null) {
3375 optional = inputs.stream()
3376 .filter(p -> p.getName()
3377 .equals(getInputIndex.getInputName()))
3379 if (!optional.isPresent()) {
3380 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3381 // @@TODO error message
3382 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
3384 InputDefinition inputIndex = optional.get();
3385 getInputIndex.setInputId(inputIndex.getUniqueId());
3386 getInputValues.add(getInputIndex);
3390 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
3391 String propName = prop.getName();
3392 if (!currPropertiesMap.containsKey(propName)) {
3393 currPropertiesMap.put(propName, prop);
3397 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3398 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
3399 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3401 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3402 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
3404 List<PropertyDefinition> listFromMap = originResource.getProperties();
3405 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3406 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
3407 StatusCode.ERROR,"ERROR Failed to find properties");
3408 log.debug("failed to find properties");
3409 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3411 if (listFromMap == null || listFromMap.isEmpty()) {
3412 return componentsUtils.getResponseFormat(ActionStatus.OK);
3414 for (PropertyDefinition prop : listFromMap) {
3415 String propName = prop.getName();
3416 if (!currPropertiesMap.containsKey(propName)) {
3417 currPropertiesMap.put(propName, prop);
3420 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3421 if (propMap != null && propMap.size() > 0) {
3422 for (List<UploadPropInfo> propertyList : propMap.values()) {
3424 UploadPropInfo propertyInfo = propertyList.get(0);
3425 String propName = propertyInfo.getName();
3426 if (!currPropertiesMap.containsKey(propName)) {
3427 log.debug("failed to find property {} ", propName);
3428 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
3429 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3431 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3432 ComponentInstanceProperty property = null;
3434 String value = null;
3435 List<GetInputValueDataDefinition> getInputs = null;
3436 boolean isValidate = true;
3437 if (propertyInfo.getValue() != null) {
3438 getInputs = propertyInfo.getGet_input();
3439 isValidate = getInputs == null || getInputs.isEmpty();
3441 value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3443 value = getPropertyJsonStringValue(propertyInfo.getValue(),
3444 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
3447 String innerType = null;
3448 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3450 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
3451 property.setValue(validatePropValue);
3453 if (getInputs != null && !getInputs.isEmpty()) {
3454 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3455 for (GetInputValueDataDefinition getInput : getInputs) {
3456 List<InputDefinition> inputs = resource.getInputs();
3457 if (inputs == null || inputs.isEmpty()) {
3458 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
3459 loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
3460 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
3462 .map(GetInputValueDataDefinition::getInputName)
3466 Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
3467 if (inputEither.isRight()) {
3468 throw inputEither.right().value();
3470 InputDefinition input = inputEither.left().value();
3471 getInput.setInputId(input.getUniqueId());
3472 getInputValues.add(getInput);
3474 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3475 if (getInputIndex != null) {
3476 Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
3478 if (inputEither.isRight()) {
3479 throw newInputEither.right().value();
3481 InputDefinition newInput = newInputEither.left().value();
3482 getInputIndex.setInputId(newInput.getUniqueId());
3484 getInputValues.add(getInputIndex);
3489 property.setGetInputValues(getInputValues);
3491 instPropList.add(property);
3492 // delete overriden property
3493 currPropertiesMap.remove(property.getName());
3496 // add rest of properties
3497 if (!currPropertiesMap.isEmpty()) {
3498 for (PropertyDefinition value : currPropertiesMap.values()) {
3499 instPropList.add(new ComponentInstanceProperty(value));
3502 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3503 return componentsUtils.getResponseFormat(ActionStatus.OK);
3506 // US740820 Relate RIs according to capability name
3507 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3508 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3509 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
3510 .equals(uploadReqInfo.getCapabilityName())) {// get
3514 return findAvailableCapability(validReq, currentCapCompInstance);
3516 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3519 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3520 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3521 CapabilityDefinition cap = null;
3522 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3523 if (!capMap.containsKey(validReq.getCapability())) {
3526 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
3528 .filter(p -> p.getName()
3529 .equals(uploadReqInfo.getCapabilityName()))
3531 if (!capByName.isPresent()) {
3534 cap = capByName.get();
3536 if (isBoundedByOccurrences(cap)) {
3537 String leftOccurrences = cap.getLeftOccurrences();
3538 int left = Integer.parseInt(leftOccurrences);
3541 cap.setLeftOccurrences(String.valueOf(left));
3549 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
3550 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
3551 if (capMap.containsKey(validReq.getCapability())) {
3552 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3554 for (CapabilityDefinition cap : capList) {
3555 if (isBoundedByOccurrences(cap)) {
3556 String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
3557 : cap.getMaxOccurrences();
3558 int left = Integer.parseInt(leftOccurrences);
3561 cap.setLeftOccurrences(String.valueOf(left));
3572 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
3573 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
3574 .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
3577 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3578 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3580 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3581 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3582 RequirementDefinition validRegDef = null;
3584 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3585 for (RequirementDefinition reqDef : entry.getValue()) {
3586 if (reqDef.getName()
3588 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3589 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3590 String leftOccurrences = reqDef.getLeftOccurrences();
3591 if (leftOccurrences == null) {
3592 leftOccurrences = reqDef.getMaxOccurrences();
3594 int left = Integer.parseInt(leftOccurrences);
3597 reqDef.setLeftOccurrences(String.valueOf(left));
3598 validRegDef = reqDef;
3604 validRegDef = reqDef;
3610 if (validRegDef != null) {
3615 for (RequirementDefinition reqDef : list) {
3616 if (reqDef.getName()
3618 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
3619 .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3620 String leftOccurrences = reqDef.getLeftOccurrences();
3621 if (leftOccurrences == null) {
3622 leftOccurrences = reqDef.getMaxOccurrences();
3624 int left = Integer.parseInt(leftOccurrences);
3627 reqDef.setLeftOccurrences(String.valueOf(left));
3628 validRegDef = reqDef;
3634 validRegDef = reqDef;
3640 if (validRegDef == null) {
3641 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3642 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3643 return Either.right(responseFormat);
3645 return Either.left(validRegDef);
3648 private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
3649 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
3651 Either<Resource, ResponseFormat> eitherResource;
3652 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3653 if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3654 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3655 throw new ByResponseFormatComponentException(responseFormat);
3657 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3658 nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
3660 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3661 uploadResInstancesMap.values()
3662 .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
3663 existingNodeTypesByResourceNames, resourcesInstancesMap));
3664 if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
3665 Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
3667 .collect(toMap(Resource::getUniqueId, r -> r));
3668 oldResource.getComponentInstances()
3670 .filter(i -> !i.isCreatedFromCsar())
3671 .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
3672 getOriginResource(existingNodeTypesByUids, uiInst)));
3675 if (isNotEmpty(resourcesInstancesMap)) {
3677 toscaOperationFacade.associateComponentInstancesToComponent(resource,
3678 resourcesInstancesMap, false, oldResource != null);
3679 } catch (StorageException exp) {
3680 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
3681 log.debug("Failed to add component instances to container component {}", resource.getName());
3682 ResponseFormat responseFormat = componentsUtils
3683 .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
3684 eitherResource = Either.right(responseFormat);
3685 throw new ByResponseFormatComponentException(eitherResource.right().value());
3689 if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
3690 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3691 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3692 BeEcompErrorManager.getInstance()
3693 .logBeDaoSystemError(
3694 "Error when create resource instance from csar. ComponentInstances list empty");
3695 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3700 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3701 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
3702 Map<ComponentInstance, Resource> resourcesInstancesMap) {
3703 Either<Resource, ResponseFormat> eitherResource;
3704 log.debug("*************Going to create resource instances {}", yamlName);
3705 // updating type if the type is node type name - we need to take the
3707 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3708 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3709 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
3710 .getToscaResourceName());
3712 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3713 existingnodeTypeMap);
3715 ComponentInstance componentInstance = new ComponentInstance();
3716 componentInstance.setComponentUid(refResource.getUniqueId());
3717 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3718 if(directives != null && !directives.isEmpty()) {
3719 componentInstance.setDirectives(new ArrayList<>(directives));
3721 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3722 if (uploadNodeFilterInfo != null){
3723 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3724 componentInstance.getUniqueId()));
3726 ComponentTypeEnum containerComponentType = resource.getComponentType();
3727 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3728 if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3729 && isNotEmpty(refResource.getCapabilities())) {
3730 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3731 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3732 refResource.getUniqueId(), refResource.getCapabilities(),
3733 uploadComponentInstanceInfo.getCapabilities());
3734 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3737 if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
3738 Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
3739 Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
3740 Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
3741 .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
3742 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
3743 Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
3744 for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
3745 ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
3746 to.setFile(entry.getValue().getFile());
3747 to.setType(entry.getValue().getType());
3748 toscaArtifacts.put(entry.getKey(), to);
3750 componentInstance.setToscaArtifacts(toscaArtifacts);
3753 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3754 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
3755 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3756 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3757 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3759 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3760 componentInstance.setName(uploadComponentInstanceInfo.getName());
3761 componentInstance.setIcon(origResource.getIcon());
3762 componentInstance.setCreatedFrom(CreatedFrom.CSAR);
3763 resourcesInstancesMap.put(componentInstance, origResource);
3766 private ComponentParametersView getComponentWithInstancesFilter() {
3767 ComponentParametersView parametersView = new ComponentParametersView();
3768 parametersView.disableAll();
3769 parametersView.setIgnoreComponentInstances(false);
3770 parametersView.setIgnoreInputs(false);
3771 // inputs are read when creating
3772 // property values on instances
3773 parametersView.setIgnoreUsers(false);
3774 return parametersView;
3777 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3778 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3779 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3780 if (originCapabilities.containsKey(currEntry.getKey())) {
3781 currEntry.getValue()
3783 .forEach(cap -> cap.setType(currEntry.getKey()));
3786 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3787 capabilities.getValue()
3790 if (uploadedCapabilities.containsKey(cap.getName())) {
3791 uploadedCapabilities.get(cap.getName())
3794 c.setName(cap.getName());
3795 c.setType(cap.getType());
3802 private Resource validateResourceInstanceBeforeCreate(String yamlName,
3803 UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
3806 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
3807 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3808 Resource refResource;
3809 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3810 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3812 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3813 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3814 if (findResourceEither.isRight()) {
3816 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type {}",
3817 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3818 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3820 refResource = findResourceEither.left().value();
3821 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3823 String componentState = refResource.getComponentMetadataDefinition()
3824 .getMetadataDataDefinition()
3826 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3828 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3829 refResource.getName(), componentState);
3830 throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
3831 refResource.getComponentType().getValue(),refResource.getName(), componentState);
3834 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3835 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3836 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
3837 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3842 public Resource propagateStateToCertified(User user, Resource resource,
3843 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3844 boolean forceCertificationAllowed) {
3846 boolean failed = false;
3848 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3849 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3850 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3852 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3853 Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
3854 resource, user, false, inTransaction, needLock, false);
3857 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3858 } catch (ComponentException e) {
3860 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3864 BeEcompErrorManager.getInstance()
3865 .logBeSystemError("Change LifecycleState - Certify");
3866 if (!inTransaction) {
3867 janusGraphDao.rollback();
3869 } else if (!inTransaction) {
3870 janusGraphDao.commit();
3875 private Resource nodeFullCertification(String uniqueId, User user,
3876 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3877 Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
3878 inTransaction, needLock);
3879 if(resourceResponse.isRight()){
3880 throw new ByResponseFormatComponentException(resourceResponse.right().value());
3882 return resourceResponse.left().value();
3885 private Resource nodeForceCertification(Resource resource, User user,
3886 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3887 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3891 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
3893 final boolean isNormative,
3894 final boolean isInTransaction,
3895 final boolean needLock,
3896 final CsarInfo csarInfo,
3897 final String nodeName,
3898 final boolean isNested) {
3900 ImmutablePair<Resource, ActionStatus> result = null;
3901 // check if resource already exists (search by tosca name = type)
3902 final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3903 final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3904 .getLatestByToscaResourceName(resource.getToscaResourceName());
3906 if (latestByToscaName.isLeft()) {
3907 Resource foundResource = latestByToscaName.left().value();
3908 // we don't allow updating names of top level types
3909 if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
3910 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3911 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3912 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3913 foundResource.getName(), resource.getToscaResourceName());
3914 final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3915 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3916 throwComponentException(responseFormat);
3918 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3919 } else if (isNotFound(latestByToscaName)) {
3920 if (isNestedResource) {
3921 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
3922 isNested, nodeName);
3924 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3927 StorageOperationStatus status = latestByToscaName.right().value();
3928 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3929 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
3930 .convertFromStorageResponse(latestByToscaName.right().value()), resource);
3931 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3932 throwComponentException(responseFormat);
3937 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3938 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3941 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
3943 final boolean isNormative,
3944 final boolean isInTransaction,
3945 final boolean needLock,
3946 final CsarInfo csarInfo,
3947 final boolean isNested,
3948 final String nodeName) {
3949 final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3950 .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
3951 .name(), csarInfo.getVfResourceName(), nodeName).getRight());
3952 if (latestByToscaName.isLeft()) {
3953 final Resource nestedResource = (Resource) latestByToscaName.left().value();
3954 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3955 final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
3956 resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3957 if (eitherValidation.isRight()) {
3958 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3960 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3962 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3966 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3967 return getResourceEither.isRight() && getResourceEither.right()
3968 .value() == StorageOperationStatus.NOT_FOUND;
3971 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
3972 boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3973 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3974 validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3975 final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
3977 Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
3978 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
3979 ASDCKpiApi.countImportResourcesKPI();
3980 return resourcePair;
3983 public boolean isResourceExist(String resourceName) {
3984 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3985 return latestByName.isLeft();
3988 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
3989 Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
3990 String lockedResourceId = oldResource.getUniqueId();
3991 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3992 oldResource.getVersion(), oldResource.getLifecycleState());
3993 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3995 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3996 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3997 mergeOldResourceMetadataWithNew(oldResource, newResource);
3999 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
4000 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
4001 // contact info normalization
4002 newResource.setContactId(newResource.getContactId().toLowerCase());
4003 PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
4004 // non-updatable fields
4005 newResource.setCreatorUserId(user.getUserId());
4006 newResource.setCreatorFullName(user.getFullName());
4007 newResource.setLastUpdaterUserId(user.getUserId());
4008 newResource.setLastUpdaterFullName(user.getFullName());
4009 newResource.setUniqueId(oldResource.getUniqueId());
4010 newResource.setVersion(oldResource.getVersion());
4011 newResource.setInvariantUUID(oldResource.getInvariantUUID());
4012 newResource.setLifecycleState(oldResource.getLifecycleState());
4013 newResource.setUUID(oldResource.getUUID());
4014 newResource.setNormalizedName(oldResource.getNormalizedName());
4015 newResource.setSystemName(oldResource.getSystemName());
4016 if (oldResource.getCsarUUID() != null) {
4017 newResource.setCsarUUID(oldResource.getCsarUUID());
4019 if (oldResource.getImportedToscaChecksum() != null) {
4020 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
4022 newResource.setAbstract(oldResource.isAbstract());
4024 if (CollectionUtils.isEmpty(newResource.getDerivedFrom())){
4025 newResource.setDerivedFrom(oldResource.getDerivedFrom());
4027 if (CollectionUtils.isEmpty(newResource.getDataTypes())){
4028 newResource.setDataTypes(oldResource.getDataTypes());
4030 if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())){
4031 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
4033 if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())){
4034 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
4037 // created without tosca artifacts - add the placeholders
4038 if (MapUtils.isEmpty(newResource.getToscaArtifacts())){
4039 setToscaArtifactsPlaceHolders(newResource, user);
4042 if (MapUtils.isEmpty(newResource.getInterfaces())){
4043 newResource.setInterfaces(oldResource.getInterfaces());
4045 if (CollectionUtils.isEmpty(newResource.getAttributes())) {
4046 newResource.setAttributes(oldResource.getAttributes());
4049 if (CollectionUtils.isEmpty(newResource.getProperties())) {
4050 newResource.setProperties(oldResource.getProperties());
4053 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
4055 if (overrideResource.isRight()) {
4056 ResponseFormat responseFormat = componentsUtils
4057 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
4058 .value()), newResource);
4059 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
4061 throwComponentException(responseFormat);
4063 updateCatalog(overrideResource.left()
4064 .value(), ChangeTypeEnum.LIFECYCLE);
4066 log.debug("Resource updated successfully!!!");
4067 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4068 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4069 ResourceVersionInfo.newBuilder()
4070 .state(oldResource.getLifecycleState()
4072 .version(oldResource.getVersion())
4075 resourcePair = new ImmutablePair<>(overrideResource.left()
4076 .value(), ActionStatus.OK);
4077 return resourcePair;
4079 if (resourcePair == null) {
4080 BeEcompErrorManager.getInstance()
4081 .logBeSystemError("Change LifecycleState - Certify");
4082 janusGraphDao.rollback();
4083 } else if (!inTransaction) {
4084 janusGraphDao.commit();
4087 log.debug("unlock resource {}", lockedResourceId);
4088 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4095 * Merge old resource with new. Keep old category and vendor name without
4098 * @param oldResource
4099 * @param newResource
4101 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4103 // keep old category and vendor name without change
4104 // merge the rest of the resource metadata
4105 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4106 newResource.setTags(oldResource.getTags());
4109 if (newResource.getDescription() == null) {
4110 newResource.setDescription(oldResource.getDescription());
4113 if (newResource.getVendorRelease() == null) {
4114 newResource.setVendorRelease(oldResource.getVendorRelease());
4117 if (newResource.getResourceVendorModelNumber() == null) {
4118 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4121 if (newResource.getContactId() == null) {
4122 newResource.setContactId(oldResource.getContactId());
4125 newResource.setCategories(oldResource.getCategories());
4126 if (newResource.getVendorName() == null) {
4127 newResource.setVendorName(oldResource.getVendorName());
4129 List<GroupDefinition>oldForUpdate = oldResource.getGroups();
4130 if(CollectionUtils.isNotEmpty(oldForUpdate)){
4131 List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
4133 groupForUpdate.stream().filter(group -> group.isVspOriginated())
4134 .forEach(group -> group.setName(group.getInvariantName()));
4136 newResource.setGroups(groupForUpdate);
4140 if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
4141 ResourceTypeEnum updatedResourceType = newResource.getResourceType();
4142 Component derivedFromResource = getParentComponent(newResource);
4143 if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
4144 Resource parentResource = (Resource) derivedFromResource;
4145 if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
4146 parentResource.getResourceType() != updatedResourceType) {
4147 BeEcompErrorManager.getInstance()
4148 .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
4149 ErrorSeverity.ERROR);
4150 log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
4151 newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
4152 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
4159 private Component getParentComponent(Resource newResource) {
4160 String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
4161 Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
4162 if(latestByToscaResourceName.isRight()){
4163 BeEcompErrorManager.getInstance()
4164 .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
4165 log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
4166 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
4168 return latestByToscaResourceName.left().value();
4171 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
4172 boolean inTransaction, boolean needLock) {
4174 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
4176 return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4177 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
4179 .on(response -> failOnChangeState(response, user, oldResource, newResource));
4184 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
4185 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
4186 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4187 ResourceVersionInfo.newBuilder()
4188 .state(oldResource.getLifecycleState()
4190 .version(oldResource.getVersion())
4192 throw new ByResponseFormatComponentException(response);
4195 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
4196 boolean inTransaction, CsarInfo csarInfo) {
4198 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4199 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4200 validateLifecycleTypesCreate(user, resource, actionEnum);
4201 validateResourceType(user, resource, actionEnum);
4202 resource.setCreatorUserId(user.getUserId());
4203 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4204 resource.setContactId(resource.getContactId()
4206 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4207 String resourceSystemName;
4208 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4209 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4211 resourceSystemName = resource.getSystemName();
4213 resource.setToscaResourceName(CommonBeUtils
4214 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4217 // Generate invariant UUID - must be here and not in operation since it
4218 // should stay constant during clone
4220 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4221 resource.setInvariantUUID(invariantUUID);
4226 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4227 AuditingActionEnum actionEnum) {
4228 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4229 if (resource.getResourceType() == null) {
4230 log.debug("Invalid resource type for resource");
4231 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4232 eitherResult = Either.right(errorResponse);
4233 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4235 return eitherResult;
4238 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4239 AuditingActionEnum actionEnum) {
4240 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4241 if (resource.getInterfaces() != null && resource.getInterfaces()
4243 log.debug("validate interface lifecycle Types Exist");
4244 Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
4247 while (intItr.hasNext() && eitherResult.isLeft()) {
4248 InterfaceDefinition interfaceDefinition = intItr.next();
4249 String intType = interfaceDefinition.getUniqueId();
4250 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4251 .getInterface(intType);
4252 if (eitherCapTypeFound.isRight()) {
4253 if (eitherCapTypeFound.right()
4254 .value() == StorageOperationStatus.NOT_FOUND) {
4255 BeEcompErrorManager.getInstance()
4256 .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
4257 "Interface", intType);
4258 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4259 intType, resource.getName());
4260 BeEcompErrorManager.getInstance()
4261 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4262 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
4267 ResponseFormat errorResponse = componentsUtils
4268 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4269 eitherResult = Either.right(errorResponse);
4270 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4275 return eitherResult;
4278 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4279 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4280 boolean inTransaction) {
4282 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4283 if (resource.getCapabilities() != null && resource.getCapabilities()
4285 log.debug("validate capability Types Exist - capabilities section");
4287 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
4290 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4291 eitherResult, typeEntry, inTransaction);
4292 if (eitherResult.isRight()) {
4293 return Either.right(eitherResult.right()
4299 if (resource.getRequirements() != null && resource.getRequirements()
4301 log.debug("validate capability Types Exist - requirements section");
4302 for (String type : resource.getRequirements()
4304 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4305 resource.getRequirements()
4307 actionEnum, eitherResult, type, inTransaction);
4308 if (eitherResult.isRight()) {
4309 return Either.right(eitherResult.right()
4315 return eitherResult;
4318 // @param typeObject- the object to which the validation is done
4319 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4320 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4321 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4322 boolean inTransaction) {
4323 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4324 .getCapabilityType(type, inTransaction);
4325 if (eitherCapTypeFound.isRight()) {
4326 if (eitherCapTypeFound.right()
4327 .value() == StorageOperationStatus.NOT_FOUND) {
4328 BeEcompErrorManager.getInstance()
4329 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4331 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4332 resource.getName());
4333 BeEcompErrorManager.getInstance()
4334 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4336 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
4339 ResponseFormat errorResponse = null;
4341 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4343 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4346 eitherResult = Either.right(errorResponse);
4347 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4349 return eitherResult;
4352 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4353 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4354 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4355 boolean inTransaction) {
4356 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4357 .getCapabilityType(typeEntry.getKey(), inTransaction);
4358 if (eitherCapTypeFound.isRight()) {
4359 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4360 BeEcompErrorManager.getInstance()
4361 .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
4362 typeEntry.getKey());
4363 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4364 typeEntry.getKey(), resource.getName());
4365 BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
4367 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4368 eitherCapTypeFound.right().value().name());
4369 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4370 typeEntry.getKey());
4371 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4372 return Either.right(errorResponse);
4374 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4375 if (capabilityTypeDefinition.getProperties() != null) {
4376 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4377 List<ComponentInstanceProperty> properties = capDef.getProperties();
4378 List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
4379 if (properties == null || properties.isEmpty()) {
4380 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4381 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4382 changedProperties.add(newProp);
4385 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4386 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4387 PropertyDefinition propFromDef = prop.getValue();
4388 boolean propFound = false;
4389 for (ComponentInstanceProperty cip : properties) {
4390 if (propFromDef.getName().equals(cip.getName())) {
4391 //merge property value and property description only, ignore other fields
4392 if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
4393 propFromDef.setDescription(cip.getDescription());
4395 propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
4396 if(cip.getValue() != null){
4397 propFromDef.setValue(cip.getValue());
4399 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4401 properties.remove(cip);
4406 propsToAdd.add(new ComponentInstanceProperty(propFromDef));
4409 if (!propsToAdd.isEmpty()) {
4410 changedProperties.addAll(propsToAdd);
4413 capDef.setProperties(changedProperties);
4416 return eitherResult;
4419 public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
4420 boolean isNormative, boolean inTransaction) {
4423 // lock new resource name in order to avoid creation resource with same
4425 Resource createdResource = null;
4426 if (!inTransaction) {
4427 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4429 if (lockResult.isRight()) {
4430 ResponseFormat responseFormat = lockResult.right().value();
4431 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4432 throw new ByResponseFormatComponentException(responseFormat);
4435 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4438 if (resource.deriveFromGeneric()) {
4439 handleResourceGenericType(resource);
4441 createdResource = createResourceTransaction(resource, user, isNormative);
4442 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4443 createdResource, actionEnum);
4444 ASDCKpiApi.countCreatedResourcesKPI();
4445 } catch (ComponentException e) {
4446 ResponseFormat responseFormat = e.getResponseFormat() == null
4447 ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
4448 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4450 } catch (StorageException e) {
4451 ResponseFormat responseFormat = componentsUtils
4452 .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
4453 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4456 if (!inTransaction) {
4457 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4458 NodeTypeEnum.Resource);
4461 return createdResource;
4464 private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
4465 // validate resource name uniqueness
4466 log.debug("validate resource name");
4467 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4468 resource.getName(), resource.getResourceType(), resource.getComponentType());
4469 if (eitherValidation.isRight()) {
4470 loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
4471 StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
4472 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4473 eitherValidation.right()
4475 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
4478 if (eitherValidation.left()
4480 log.debug("resource with name: {}, already exists", resource.getName());
4481 loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
4482 StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
4483 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4484 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4487 log.debug("send resource {} to dao for create", resource.getName());
4489 createArtifactsPlaceHolderData(resource, user);
4492 log.debug("enrich resource with creator, version and state");
4493 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4494 resource.setVersion(INITIAL_VERSION);
4495 resource.setHighestVersion(true);
4496 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4497 resource.setAbstract(false);
4500 return toscaOperationFacade.createToscaComponent(resource)
4502 .on(r -> throwComponentExceptionByResource(r, resource));
4505 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
4506 ResponseFormat responseFormat = componentsUtils
4507 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
4508 throw new ByResponseFormatComponentException(responseFormat);
4511 private void createArtifactsPlaceHolderData(Resource resource, User user) {
4512 // create mandatory artifacts
4514 // TODO it must be removed after that artifact uniqueId creation will be
4515 // moved to ArtifactOperation
4517 setInformationalArtifactsPlaceHolder(resource, user);
4518 setDeploymentArtifactsPlaceHolder(resource, user);
4519 setToscaArtifactsPlaceHolders(resource, user);
4522 @SuppressWarnings("unchecked")
4524 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4525 Resource resource = (Resource) component;
4526 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4527 if (artifactMap == null) {
4528 artifactMap = new HashMap<>();
4530 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4532 .getDeploymentResourceArtifacts();
4533 if (deploymentResourceArtifacts != null) {
4534 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
4535 deploymentResourceArtifacts
4536 .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
4538 resource.setDeploymentArtifacts(artifactMap);
4541 private void processDeploymentResourceArtifacts(User user, Resource resource,
4542 Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
4543 boolean shouldCreateArtifact = true;
4544 Map<String, Object> artifactDetails = (Map<String, Object>) v;
4545 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4546 if (object != null) {
4547 List<String> artifactTypes = (List<String>) object;
4548 if (!artifactTypes.contains(resource.getResourceType()
4550 shouldCreateArtifact = false;
4554 log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
4556 if (shouldCreateArtifact) {
4557 if (artifactsBusinessLogic != null) {
4558 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4559 resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
4560 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
4561 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4567 @SuppressWarnings("unchecked")
4568 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4569 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4570 if (artifactMap == null) {
4571 artifactMap = new HashMap<>();
4573 String resourceUniqueId = resource.getUniqueId();
4574 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
4576 .getExcludeResourceCategory();
4577 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
4579 .getExcludeResourceType();
4580 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4582 .getInformationalResourceArtifacts();
4583 List<CategoryDefinition> categories = resource.getCategories();
4584 boolean isCreateArtifact = true;
4585 if (exludeResourceCategory != null) {
4586 String category = categories.get(0)
4588 isCreateArtifact = exludeResourceCategory.stream()
4589 .noneMatch(e -> e.equalsIgnoreCase(category));
4591 if (isCreateArtifact && exludeResourceType != null) {
4592 String resourceType = resource.getResourceType()
4594 isCreateArtifact = exludeResourceType.stream()
4595 .noneMatch(e -> e.equalsIgnoreCase(resourceType));
4597 if (informationalResourceArtifacts != null && isCreateArtifact) {
4598 Set<String> keys = informationalResourceArtifacts.keySet();
4599 for (String informationalResourceArtifactName : keys) {
4600 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4601 .get(informationalResourceArtifactName);
4602 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4603 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4604 ArtifactGroupTypeEnum.INFORMATIONAL);
4605 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4609 resource.setArtifacts(artifactMap);
4619 public ResponseFormat deleteResource(String resourceId, User user) {
4620 ResponseFormat responseFormat;
4621 validateUserExists(user);
4623 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4624 if (resourceStatus.isRight()) {
4625 log.debug("failed to get resource {}", resourceId);
4626 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4630 Resource resource = resourceStatus.left()
4633 StorageOperationStatus result = StorageOperationStatus.OK;
4634 lockComponent(resourceId, resource, "Mark resource to delete");
4637 result = markComponentToDelete(resource);
4638 if (result == StorageOperationStatus.OK) {
4639 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4641 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4642 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4644 return responseFormat;
4647 if (result == null || result != StorageOperationStatus.OK) {
4648 janusGraphDao.rollback();
4650 janusGraphDao.commit();
4652 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
4657 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
4658 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4659 validateUserExists(user);
4660 Resource resource = null;
4661 StorageOperationStatus result = StorageOperationStatus.OK;
4662 boolean failed = false;
4665 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
4666 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
4667 if (resourceStatus.isRight()) {
4668 log.debug("failed to get resource {} version {}", resourceName, version);
4669 return componentsUtils
4670 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
4671 .value()), resourceName);
4674 resource = resourceStatus.left()
4678 janusGraphDao.commit();
4680 if (resource != null) {
4681 lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
4683 result = markComponentToDelete(resource);
4684 if (result != StorageOperationStatus.OK) {
4685 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4686 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4687 return responseFormat;
4689 }catch (ComponentException e){
4693 if (failed || result == null || result != StorageOperationStatus.OK) {
4694 janusGraphDao.rollback();
4696 janusGraphDao.commit();
4698 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
4701 return responseFormat;
4704 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
4707 validateUserExists(user);
4710 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
4711 if (storageStatus.isRight()) {
4712 log.debug("failed to get resource by id {}", resourceId);
4713 return Either.right(componentsUtils
4714 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
4715 .value()), resourceId));
4717 if (!(storageStatus.left()
4718 .value() instanceof Resource)) {
4719 return Either.right(componentsUtils.getResponseFormatByResource(
4720 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4722 return Either.left(storageStatus.left()
4727 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4730 validateUserExists(userId);
4732 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4733 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4734 if (getResource.isRight()) {
4735 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4736 return Either.right(componentsUtils
4737 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
4738 .value()), resourceName));
4740 return Either.left(getResource.left()
4745 * updateResourceMetadata
4748 * - modifier data (userId)
4749 * @param inTransaction
4751 * @param resourceIdToUpdate
4752 * - the resource identifier
4753 * @param newResource
4754 * @return Either<Resource , responseFormat>
4756 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
4757 User user, boolean inTransaction) {
4759 validateUserExists(user.getUserId());
4761 log.debug("Get resource with id {}", resourceIdToUpdate);
4762 boolean needToUnlock = false;
4765 if (currentResource == null) {
4766 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4767 .getToscaElement(resourceIdToUpdate);
4768 if (storageStatus.isRight()) {
4769 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4770 componentsUtils.convertFromStorageResponse(storageStatus.right()
4775 currentResource = storageStatus.left()
4778 // verify that resource is checked-out and the user is the last
4780 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4781 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4785 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4786 NodeTypeEnum.Resource);
4787 if (lockResult != StorageOperationStatus.OK) {
4788 BeEcompErrorManager.getInstance()
4789 .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
4790 resourceIdToUpdate);
4791 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4792 ResponseFormat responseFormat = componentsUtils
4793 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4794 throw new ByResponseFormatComponentException(responseFormat);
4797 needToUnlock = true;
4799 // critical section starts here
4800 // convert json to object
4802 // Update and updated resource must have a non-empty "derivedFrom"
4804 // This code is not called from import resources, because of root
4805 // VF "derivedFrom" should be null (or ignored)
4806 if (ModelConverter.isAtomicComponent(currentResource)) {
4807 validateDerivedFromNotEmpty(null, newResource, null);
4808 validateDerivedFromNotEmpty(null, currentResource, null);
4810 newResource.setDerivedFrom(null);
4813 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4814 user, currentResource, false, true);
4815 if (dataModelResponse.isRight()) {
4816 log.debug("failed to update resource metadata!!!");
4817 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4820 log.debug("Resource metadata updated successfully!!!");
4821 return dataModelResponse.left()
4824 } catch (ComponentException | StorageException e) {
4825 rollback(inTransaction, newResource, null, null);
4828 if (!inTransaction) {
4829 janusGraphDao.commit();
4832 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4837 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4838 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4839 updateVfModuleGroupsNames(currentResource, newResource);
4840 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4841 // Setting last updater and uniqueId
4842 newResource.setContactId(newResource.getContactId()
4844 newResource.setLastUpdaterUserId(user.getUserId());
4845 newResource.setUniqueId(resourceIdToUpdate);
4846 // Cannot set highest version through UI
4847 newResource.setHighestVersion(currentResource.isHighestVersion());
4848 newResource.setCreationDate(currentResource.getCreationDate());
4850 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4851 newResource, user.getUserId(), inTransaction);
4853 if (processUpdateOfDerivedFrom.isRight()) {
4854 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4855 return Either.right(processUpdateOfDerivedFrom.right()
4859 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4860 if (isNotEmpty(newResource.getGroups())) {
4861 for (GroupDefinition group : newResource.getGroups()) {
4862 if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
4863 groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
4864 .getMetadataDataDefinition()
4865 .getUniqueId(), user, newResource.getComponentType(), group, true, false);
4869 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4870 .updateToscaElement(newResource);
4872 if (dataModelResponse.isRight()) {
4873 ResponseFormat responseFormat = componentsUtils
4874 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
4875 .value()), newResource);
4876 return Either.right(responseFormat);
4877 } else if (dataModelResponse.left()
4879 log.debug("No response from updateResource");
4880 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4882 return Either.left(dataModelResponse.left()
4886 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4887 if (currentResource.getGroups() != null && !currentResource.getName()
4888 .equals(newResource.getName())) {
4889 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4891 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4893 newResource.setGroups(updatedGroups);
4897 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4898 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4899 if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
4900 .equals(DEFAULT_GROUP_VF_MODULE)) {
4901 String prefix = updatedGroup.getName()
4902 .substring(0, replacePattern.length());
4903 String newGroupName = updatedGroup.getName()
4904 .replaceFirst(prefix, with);
4905 updatedGroup.setName(newGroupName);
4907 return updatedGroup;
4911 * validateResourceFieldsBeforeCreate
4914 * - modifier data (userId)
4916 private void validateResourceFieldsBeforeCreate(User user, Resource resource,
4917 AuditingActionEnum actionEnum, boolean inTransaction) {
4918 componentValidator.validate(user, resource, actionEnum);
4919 // validate category
4920 log.debug("validate category");
4921 validateCategory(user, resource, actionEnum, inTransaction);
4922 // validate vendor name & release & model number
4923 log.debug("validate vendor name");
4924 validateVendorName(user, resource, actionEnum);
4925 log.debug("validate vendor release");
4926 validateVendorReleaseName(user, resource, actionEnum);
4927 log.debug("validate resource vendor model number");
4928 validateResourceVendorModelNumber(user, resource, actionEnum);
4930 log.debug("validate cost");
4931 validateCost(resource);
4932 // validate licenseType
4933 log.debug("validate licenseType");
4934 validateLicenseType(user, resource, actionEnum);
4935 // validate template (derived from)
4936 log.debug("validate derived from");
4937 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4938 resource.setDerivedFrom(null);
4940 validateDerivedFromExist(user, resource, actionEnum);
4941 // warn about non-updatable fields
4942 checkComponentFieldsForOverrideAttempt(resource);
4943 String currentCreatorFullName = resource.getCreatorFullName();
4944 if (currentCreatorFullName != null) {
4945 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4948 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4949 if (currentLastUpdaterFullName != null) {
4950 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4953 Long currentLastUpdateDate = resource.getLastUpdateDate();
4954 if (currentLastUpdateDate != null) {
4955 log.debug("Resource last update date is automatically set and cannot be updated");
4958 Boolean currentAbstract = resource.isAbstract();
4959 if (currentAbstract != null) {
4960 log.debug("Resource abstract is automatically set and cannot be updated");
4965 * validateResourceFieldsBeforeUpdate
4967 * @param currentResource
4968 * - Resource object to validate
4971 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4972 boolean inTransaction, boolean isNested) {
4973 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4974 warnNonEditableFields(currentResource, updateInfoResource);
4977 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4978 String currentResourceVersion = currentResource.getVersion();
4979 String updatedResourceVersion = updateInfoResource.getVersion();
4981 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4982 log.debug("Resource version is automatically set and cannot be updated");
4985 String currentCreatorUserId = currentResource.getCreatorUserId();
4986 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4988 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4989 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4992 String currentCreatorFullName = currentResource.getCreatorFullName();
4993 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4995 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4996 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4999 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
5000 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
5002 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
5003 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
5006 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
5007 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
5009 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
5010 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
5012 Long currentCreationDate = currentResource.getCreationDate();
5013 Long updatedCreationDate = updateInfoResource.getCreationDate();
5015 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
5016 log.debug("Resource Creation date is automatically set and cannot be updated");
5019 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
5020 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
5022 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
5023 log.debug("Resource last update date is automatically set and cannot be updated");
5026 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
5027 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
5029 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
5030 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
5033 Boolean currentAbstract = currentResource.isAbstract();
5034 Boolean updatedAbstract = updateInfoResource.isAbstract();
5036 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
5037 log.debug("Resource abstract is automatically set and cannot be updated");
5040 Boolean currentHighestVersion = currentResource.isHighestVersion();
5041 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
5043 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
5044 log.debug("Resource highest version is automatically set and cannot be updated");
5047 String currentUuid = currentResource.getUUID();
5048 String updatedUuid = updateInfoResource.getUUID();
5050 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
5051 log.debug("Resource UUID is automatically set and cannot be updated");
5054 log.debug("Resource Type cannot be updated");
5055 String currentInvariantUuid = currentResource.getInvariantUUID();
5056 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
5058 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5059 log.debug("Resource invariant UUID is automatically set and cannot be updated");
5060 updateInfoResource.setInvariantUUID(currentInvariantUuid);
5064 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
5066 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5067 log.debug("validate resource name before update");
5068 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
5069 log.debug("validate description before update");
5070 componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
5071 log.debug("validate icon before update");
5072 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5073 log.debug("validate tags before update");
5074 componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
5075 log.debug("validate vendor name before update");
5076 validateVendorName(null, updateInfoResource, null);
5077 log.debug("validate resource vendor model number before update");
5078 validateResourceVendorModelNumber(currentResource, updateInfoResource);
5079 log.debug("validate vendor release before update");
5080 validateVendorReleaseName(null, updateInfoResource, null);
5081 log.debug("validate contact info before update");
5082 componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
5083 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
5084 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5085 log.debug("validate category before update");
5086 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5089 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5090 String resourceNameUpdated = updateInfoResource.getName();
5091 String resourceNameCurrent = currentResource.getName();
5092 if (resourceNameCurrent.equals(resourceNameUpdated)) {
5095 // In case of CVFC type we should support the case of old VF with CVFC
5096 // instances that were created without the "Cvfc" suffix
5097 return currentResource.getResourceType() == ResourceTypeEnum.CVFC
5098 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5101 private String addCvfcSuffixToResourceName(String resourceName) {
5102 return resourceName + "Cvfc";
5105 private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
5107 String resourceNameUpdated = updateInfoResource.getName();
5108 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5109 if (isNested || !hasBeenCertified) {
5110 componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
5111 validateResourceNameUniqueness(updateInfoResource);
5112 currentResource.setName(resourceNameUpdated);
5113 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5114 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5117 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5118 resourceNameUpdated);
5119 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5124 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5125 String iconUpdated = updateInfoResource.getIcon();
5126 String iconCurrent = currentResource.getIcon();
5127 if (!iconCurrent.equals(iconUpdated)) {
5128 if (!hasBeenCertified) {
5129 componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
5131 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5132 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5137 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
5138 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5139 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5140 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5141 validateResourceVendorModelNumber(null, updateInfoResource, null);
5145 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5146 boolean hasBeenCertified, boolean inTransaction) {
5147 validateCategory(null, updateInfoResource, null, inTransaction);
5148 if (hasBeenCertified) {
5149 CategoryDefinition currentCategory = currentResource.getCategories()
5151 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
5153 CategoryDefinition updateCategory = updateInfoResource.getCategories()
5155 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
5157 if (!currentCategory.getName()
5158 .equals(updateCategory.getName())
5159 || !currentSubCategory.getName()
5160 .equals(updtaeSubCategory.getName())) {
5161 log.info("Category {} cannot be updated once the resource has been certified once.",
5162 currentResource.getCategories());
5163 ResponseFormat errorResponse = componentsUtils
5164 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5165 return Either.right(errorResponse);
5168 return Either.left(true);
5171 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5172 Resource updateInfoResource, boolean hasBeenCertified) {
5174 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5175 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5176 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5177 || updatedDerivedFrom.isEmpty()) {
5178 log.trace("Update normative types");
5179 return Either.left(true);
5182 String derivedFromCurrent = currentDerivedFrom.get(0);
5183 String derivedFromUpdated = updatedDerivedFrom.get(0);
5185 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5186 if (!hasBeenCertified) {
5187 validateDerivedFromExist(null, updateInfoResource, null);
5189 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5190 currentResource, updateInfoResource, null);
5192 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5194 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5195 return validateDerivedFromExtending;
5199 // For derived from, we must know whether it was actually changed,
5200 // otherwise we must do no action.
5201 // Due to changes it inflicts on data model (remove artifacts,
5202 // properties...), it's not like a flat field which can be
5203 // overwritten if not changed.
5204 // So we must indicate that derived from is not changed
5205 updateInfoResource.setDerivedFrom(null);
5207 return Either.left(true);
5210 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5211 Resource updateInfoResource, boolean hasBeenCertified) {
5213 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5214 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5215 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5216 || updatedDerivedFrom.isEmpty()) {
5217 log.trace("Update normative types");
5218 return Either.left(true);
5221 String derivedFromCurrent = currentDerivedFrom.get(0);
5222 String derivedFromUpdated = updatedDerivedFrom.get(0);
5224 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5225 if (!hasBeenCertified) {
5226 validateDerivedFromExist(null, updateInfoResource, null);
5228 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5229 currentResource, updateInfoResource, null);
5231 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
5233 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5234 return validateDerivedFromExtending;
5238 return Either.left(true);
5241 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5242 if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
5246 String templateName = resource.getDerivedFrom()
5248 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5249 .validateToscaResourceNameExists(templateName);
5250 if (dataModelResponse.isRight()) {
5251 StorageOperationStatus storageStatus = dataModelResponse.right()
5253 BeEcompErrorManager.getInstance()
5254 .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5255 log.debug("request to data model failed with error: {}", storageStatus);
5256 ResponseFormat responseFormat = componentsUtils
5257 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5258 log.trace("audit before sending response");
5259 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5260 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
5261 } else if (!dataModelResponse.left()
5263 log.info("resource template with name: {}, does not exists", templateName);
5264 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5265 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5266 throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5270 // Tal G for extending inheritance US815447
5271 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5272 Resource updateInfoResource, AuditingActionEnum actionEnum) {
5273 String currentTemplateName = currentResource.getDerivedFrom()
5275 String updatedTemplateName = updateInfoResource.getDerivedFrom()
5278 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5279 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5280 if (dataModelResponse.isRight()) {
5281 StorageOperationStatus storageStatus = dataModelResponse.right()
5283 BeEcompErrorManager.getInstance()
5284 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5285 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5286 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5287 log.trace("audit before sending response");
5288 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5289 return Either.right(responseFormat);
5292 if (!dataModelResponse.left()
5294 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5295 currentTemplateName);
5296 ResponseFormat responseFormat = componentsUtils
5297 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5298 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5300 return Either.right(responseFormat);
5303 return Either.left(true);
5306 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5307 log.debug("validate resource derivedFrom field");
5308 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
5310 || (resource.getDerivedFrom()
5312 || (resource.getDerivedFrom()
5316 log.info("derived from (template) field is missing for the resource");
5317 ResponseFormat responseFormat = componentsUtils
5318 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5319 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5321 throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5325 private void validateResourceNameUniqueness(Resource resource) {
5327 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5328 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5329 resource.getComponentType());
5330 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
5332 log.debug("resource with name: {}, already exists", resource.getName());
5333 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
5334 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5335 } else if (resourceOperationResponse.isRight()) {
5336 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5337 throw new StorageException(resourceOperationResponse.right()
5342 private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5344 List<CategoryDefinition> categories = resource.getCategories();
5345 if (CollectionUtils.isEmpty(categories)) {
5346 log.debug(CATEGORY_IS_EMPTY);
5347 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5348 ComponentTypeEnum.RESOURCE.getValue());
5349 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5350 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5351 ComponentTypeEnum.RESOURCE.getValue());
5353 if (categories.size() > 1) {
5354 log.debug("Must be only one category for resource");
5355 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
5356 ComponentTypeEnum.RESOURCE.getValue());
5358 CategoryDefinition category = categories.get(0);
5359 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5360 if (CollectionUtils.isEmpty(subcategories)) {
5361 log.debug("Missinig subcategory for resource");
5362 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5364 if (subcategories.size() > 1) {
5365 log.debug("Must be only one sub category for resource");
5366 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5369 SubCategoryDefinition subcategory = subcategories.get(0);
5371 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5372 log.debug(CATEGORY_IS_EMPTY);
5373 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5374 ComponentTypeEnum.RESOURCE.getValue());
5375 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5376 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
5377 ComponentTypeEnum.RESOURCE.getValue());
5379 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5380 log.debug(CATEGORY_IS_EMPTY);
5381 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5382 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5383 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5384 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
5385 ComponentTypeEnum.RESOURCE.getValue());
5388 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
5391 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
5392 Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5393 ResponseFormat responseFormat;
5394 if (category != null && subcategory != null) {
5395 log.debug("validating resource category {} against valid categories list", category);
5396 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5397 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5398 if (categories.isRight()) {
5399 log.debug("failed to retrieve resource categories from JanusGraph");
5400 responseFormat = componentsUtils.getResponseFormat(categories.right()
5402 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5403 throw new ByActionStatusComponentException(categories.right()
5406 List<CategoryDefinition> categoryList = categories.left()
5408 Optional<CategoryDefinition> foundCategory = categoryList.stream()
5409 .filter(cat -> cat.getName()
5410 .equals(category.getName()))
5412 if (!foundCategory.isPresent()) {
5413 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5414 category, categoryList);
5415 failOnInvalidCategory(user, resource, actionEnum);
5417 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
5420 .filter(subcat -> subcat.getName()
5421 .equals(subcategory.getName()))
5423 if (!foundSubcategory.isPresent()) {
5425 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5426 subcategory, foundCategory.get()
5427 .getSubcategories());
5428 failOnInvalidCategory(user, resource, actionEnum);
5433 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
5434 ResponseFormat responseFormat;
5435 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5436 ComponentTypeEnum.RESOURCE.getValue());
5437 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5438 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5441 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
5442 String vendorRelease = resource.getVendorRelease();
5443 log.debug("validate vendor relese name");
5444 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5445 log.info("vendor relese name is missing.");
5446 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5447 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5448 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
5451 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
5454 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
5455 AuditingActionEnum actionEnum) {
5456 if (vendorRelease != null) {
5457 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
5458 log.info("vendor release exceds limit.");
5459 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5460 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5461 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5462 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
5463 "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
5466 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
5467 log.info("vendor release is not valid.");
5468 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
5469 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5470 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
5475 private void validateVendorName(User user, Resource resource,
5476 AuditingActionEnum actionEnum) {
5477 String vendorName = resource.getVendorName();
5478 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
5479 log.info("vendor name is missing.");
5480 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
5481 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5482 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
5484 validateVendorName(vendorName, user, resource, actionEnum);
5487 private void validateVendorName(String vendorName, User user, Resource resource,
5488 AuditingActionEnum actionEnum) {
5489 if (vendorName != null) {
5490 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
5491 log.info("vendor name exceds limit.");
5492 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5493 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5494 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5495 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
5496 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
5499 if (!ValidationUtils.validateVendorName(vendorName)) {
5500 log.info("vendor name is not valid.");
5501 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
5502 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5503 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME, vendorName);
5508 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
5509 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
5510 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
5511 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
5512 log.info("resource vendor model number exceeds limit.");
5513 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5514 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5515 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5516 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5517 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
5518 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
5520 // resource vendor model number is currently validated as vendor
5522 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
5523 log.info("resource vendor model number is not valid.");
5524 ResponseFormat errorResponse = componentsUtils
5525 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5526 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5527 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
5533 private void validateCost(Resource resource) {
5534 String cost = resource.getCost();
5536 if (!ValidationUtils.validateCost(cost)) {
5537 log.debug("resource cost is invalid.");
5538 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5543 private void validateLicenseType(User user, Resource resource,
5544 AuditingActionEnum actionEnum) {
5545 log.debug("validate licenseType");
5546 String licenseType = resource.getLicenseType();
5547 if (licenseType != null) {
5548 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
5550 if (!licenseTypes.contains(licenseType)) {
5551 log.debug("License type {} isn't configured", licenseType);
5552 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5553 if (actionEnum != null) {
5554 // In update case, no audit is required
5555 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5557 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
5562 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
5563 Resource updatedResource, String userId, boolean inTransaction) {
5564 if (updatedResource.getDerivedFrom() != null) {
5565 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
5566 log.debug("1. Removing interface artifacts from graph");
5567 // Remove all interface artifacts of resource
5568 String resourceId = updatedResource.getUniqueId();
5569 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
5571 if (interfaces != null) {
5572 Collection<InterfaceDefinition> values = interfaces.values();
5573 for (InterfaceDefinition interfaceDefinition : values) {
5574 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
5576 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
5577 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
5578 if (operations != null) {
5579 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
5580 Operation operation = operationEntry.getValue();
5581 ArtifactDefinition implementation = operation.getImplementationArtifact();
5582 if (implementation != null) {
5583 String uniqueId = implementation.getUniqueId();
5584 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
5585 uniqueId, operationEntry.getKey(), interfaceType);
5586 // only thing that transacts and locks here
5587 Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface =
5588 artifactsBusinessLogic.deleteArtifactByInterface(resourceId, userId, uniqueId, true);
5589 if (deleteArtifactByInterface.isRight()) {
5590 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
5591 if (!inTransaction) {
5592 janusGraphDao.rollback();
5594 return Either.right(deleteArtifactByInterface.right()
5598 log.trace("No implementation found for operation {} - nothing to delete",
5599 operationEntry.getKey());
5603 log.trace("No operations found for interface type {}", interfaceType);
5607 log.debug("2. Removing properties");
5608 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
5609 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
5611 if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
5612 log.debug("Failed to remove all properties of resource");
5613 if (!inTransaction) {
5614 janusGraphDao.rollback();
5616 return Either.right(componentsUtils
5617 .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
5622 log.debug("Derived from wasn't changed during update");
5625 if (inTransaction) {
5626 return Either.left(true);
5628 janusGraphDao.commit();
5629 return Either.left(true);
5633 /**** Auditing *******************/
5635 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
5636 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
5637 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
5639 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
5641 return webApplicationContext.getBean(class1);
5644 public ICapabilityTypeOperation getCapabilityTypeOperation() {
5645 return capabilityTypeOperation;
5649 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
5650 this.capabilityTypeOperation = capabilityTypeOperation;
5653 public Boolean validatePropertiesDefaultValues(Resource resource) {
5654 log.debug("validate resource properties default values");
5655 List<PropertyDefinition> properties = resource.getProperties();
5656 if (properties != null) {
5657 iterateOverProperties(properties);
5662 public void iterateOverProperties(List<PropertyDefinition> properties) {
5664 String innerType = null;
5665 for (PropertyDefinition property : properties) {
5666 if (!propertyOperation.isPropertyTypeValid(property)) {
5667 log.info("Invalid type for property {}", property);
5668 throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
5669 property.getType(), property.getName());
5672 Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
5673 type = property.getType();
5675 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5676 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
5677 if (responseFormat != null) {
5681 validateDefaultPropertyValue(property, allDataTypes, type, innerType);
5685 private void validateDefaultPropertyValue(PropertyDefinition property,
5686 Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
5687 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
5688 log.info("Invalid default value for property {}", property);
5689 ResponseFormat responseFormat;
5690 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
5691 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
5692 property.getName(), type, innerType, property.getDefaultValue());
5694 throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
5695 property.getName(), type, property.getDefaultValue());
5699 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
5700 Map<String, DataTypeDefinition> allDataTypes) {
5701 ResponseFormat responseFormat = null;
5702 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
5704 innerType = propertyInnerTypeValid.getLeft();
5705 if (!propertyInnerTypeValid.getRight()
5707 log.info("Invalid inner type for property {}", property);
5708 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
5709 property.getName());
5711 return responseFormat;
5715 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
5716 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
5720 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
5721 return componentInstanceBusinessLogic;
5724 private String getComponentTypeForResponse(Component component) {
5725 String componentTypeForResponse = "SERVICE";
5726 if (component instanceof Resource) {
5727 componentTypeForResponse = ((Resource) component).getResourceType()
5730 return componentTypeForResponse;
5733 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
5736 validateUserExists(user);
5738 // get resource from csar uuid
5739 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
5740 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
5741 if (either.isRight()) {
5742 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
5744 return Either.right(resp);
5747 return Either.left(either.left()
5752 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5753 String componentId, String userId) {
5757 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
5758 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5759 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5761 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5762 uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
5763 defaultCapabilities, validCapabilitiesMap));
5764 return validCapabilitiesMap;
5767 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
5768 Map<String, List<CapabilityDefinition>> defaultCapabilities,
5769 Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
5770 String capabilityType = capabilities.get(0)
5772 if (defaultCapabilities.containsKey(capabilityType)) {
5773 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5774 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5775 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5776 validCapabilityList.add(defaultCapability);
5777 validCapabilitiesMap.put(key, validCapabilityList);
5779 throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
5783 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
5784 CapabilityDefinition defaultCapability) {
5785 if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
5786 .getProperties())) {
5787 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5788 defaultCapability.getName(), resourceId);
5789 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
5790 defaultCapability.getName());
5791 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
5792 } else if (isNotEmpty(capabilities.get(0)
5793 .getProperties())) {
5794 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5798 private CapabilityDefinition getCapability(String resourceId,
5799 Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5800 CapabilityDefinition defaultCapability;
5801 if (isNotEmpty(defaultCapabilities.get(capabilityType)
5803 .getProperties())) {
5804 defaultCapability = defaultCapabilities.get(capabilityType)
5807 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5808 .getToscaFullElement(resourceId);
5809 if (getFullComponentRes.isRight()) {
5810 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
5812 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
5814 defaultCapability = getFullComponentRes.left()
5817 .get(capabilityType)
5820 return defaultCapability;
5823 private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
5824 UploadCapInfo uploadedCapability) {
5825 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5826 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
5828 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5829 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5830 for (UploadPropInfo property : uploadedProperties) {
5831 String propertyName = property.getName()
5833 String propertyType = property.getType();
5834 ComponentInstanceProperty validProperty;
5835 if (defaultProperties.containsKey(propertyName)
5836 && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5837 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
5839 validProperty = new ComponentInstanceProperty();
5840 validProperty.setName(propertyName);
5841 if (property.getValue() != null) {
5842 validProperty.setValue(property.getValue()
5845 validProperty.setDescription(property.getDescription());
5846 validProperty.setPassword(property.isPassword());
5847 validProperties.add(validProperty);
5849 defaultCapability.setProperties(validProperties);
5852 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
5853 String propertyType) {
5854 return propertyType != null && !defaultProperties.get(propertyName)
5856 .equals(propertyType);
5859 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5860 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5861 Resource resource, User user) {
5863 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5864 ArtifactOperationEnum.class);
5865 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5866 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5867 .left(nodeTypeArtifactsToHandle);
5869 // add all found Csar artifacts to list to upload
5870 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5871 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5872 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5873 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5874 ArtifactDefinition foundArtifact;
5876 if (!existingArtifactsToHandle.isEmpty()) {
5877 foundArtifact = existingArtifactsToHandle.stream()
5878 .filter(a -> a.getArtifactName()
5879 .equals(currNewArtifact.getArtifactName()))
5882 if (foundArtifact != null) {
5883 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
5884 if (!foundArtifact.getArtifactChecksum()
5885 .equals(currNewArtifact.getArtifactChecksum())) {
5886 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5887 // if current artifact already exists, but has
5888 // different content, add him to the list to
5890 artifactsToUpdate.add(currNewArtifact);
5892 // remove found artifact from the list of existing
5893 // artifacts to handle, because it was already
5895 existingArtifactsToHandle.remove(foundArtifact);
5896 // and remove found artifact from the list to
5897 // upload, because it should either be updated or be
5899 artifactsToUpload.remove(currNewArtifact);
5901 log.debug("Can't upload two artifact with the same name {}.",
5902 currNewArtifact.getArtifactName());
5903 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
5904 .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5905 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
5906 foundArtifact.getArtifactType());
5907 AuditingActionEnum auditingAction = artifactsBusinessLogic
5908 .detectAuditingType(new ArtifactOperationInfo(false, false,
5909 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5910 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5911 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5912 resource.getComponentType(), null);
5913 responseWrapper.setInnerElement(responseFormat);
5919 if (responseWrapper.isEmpty()) {
5920 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5921 if (currArtifact.getIsFromCsar()) {
5922 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5923 currArtifact.getArtifactType(),
5924 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5925 currArtifact.getIsFromCsar()));
5927 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
5928 currArtifact.getArtifactType(),
5929 currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
5930 currArtifact.getIsFromCsar()));
5935 if (responseWrapper.isEmpty()) {
5936 if (!artifactsToUpload.isEmpty()) {
5937 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5939 if (!artifactsToUpdate.isEmpty()) {
5940 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5942 if (!artifactsToDelete.isEmpty()) {
5943 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5946 if (!responseWrapper.isEmpty()) {
5947 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5949 } catch (Exception e) {
5950 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5951 responseWrapper.setInnerElement(responseFormat);
5952 log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5954 return nodeTypeArtifactsToHandleRes;
5957 ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
5958 final String vfResourceName,
5959 final String nodeTypeFullName) {
5961 String actualVfName;
5962 if (ResourceTypeEnum.CVFC.name()
5963 .equals(nodeResourceType)) {
5964 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5965 actualType = ResourceTypeEnum.VFC.name();
5967 actualVfName = vfResourceName;
5968 actualType = nodeResourceType;
5970 String nameWithouNamespacePrefix;
5972 final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
5973 log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
5974 + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName,
5975 nodeTypeFullName, actualType, vfResourceName);
5976 final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
5978 if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
5979 nameWithouNamespacePrefix = nodeTypeFullName;
5981 nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
5983 final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5985 if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
5986 actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
5988 actualName = "." + nameWithouNamespacePrefix;
5991 if (actualName.startsWith(Constants.ABSTRACT)) {
5992 toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
5993 .append(ValidationUtils.convertToSystemName(actualVfName));
5995 toscaResourceName.append(actualType.toLowerCase()).append('.')
5996 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5998 final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5999 final String[] actualNames = actualName.split("\\.");
6000 if (actualNames.length < 3) {
6001 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
6002 previousToscaResourceName.append(actualName).toString());
6004 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
6005 previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
6006 .toLowerCase()).toString());
6007 } catch (final Exception e) {
6008 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
6009 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
6014 * Extracts a Node Type Name prefix from the given Node Type Name.
6016 * @param fullName Node Type Name
6017 * @return Node Type Name Prefix
6019 private String getNodeTypeNamePrefix(final String fullName) {
6020 String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
6021 final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
6022 log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
6023 final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
6024 if (validNameSpace.isPresent()) {
6025 tempPrefix = validNameSpace.get();
6027 log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
6032 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
6033 List<String> dataParamsToReturn) {
6035 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
6036 Either<Resource, StorageOperationStatus> resourceResultEither =
6037 toscaOperationFacade.getToscaElement(resourceId,
6040 if (resourceResultEither.isRight()) {
6041 if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
6042 log.debug("Failed to found resource with id {} ", resourceId);
6044 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
6047 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
6048 return Either.right(componentsUtils
6049 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
6053 Resource resource = resourceResultEither.left().value();
6054 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
6055 ListUtils.emptyIfNull(resource.getInputs())
6056 .forEach(input -> input.setConstraints(setInputConstraint(input)));
6059 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
6060 dataParamsToReturn);
6061 return Either.left(dataTransfer);
6065 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
6066 Resource resource = (Resource) clonedComponent;
6067 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
6068 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
6069 .shouldUpgradeToLatestDerived(resource);
6070 if (shouldUpgradeToLatestDerived.isRight()) {
6071 return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
6074 return Either.left(shouldUpgradeToLatestDerived.left()
6077 return super.shouldUpgradeToLatestDerived(clonedComponent);