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=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
26 import static java.util.stream.Collectors.joining;
27 import static java.util.stream.Collectors.toList;
28 import static java.util.stream.Collectors.toMap;
29 import static java.util.stream.Collectors.toSet;
30 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
31 import static org.apache.commons.collections.MapUtils.isEmpty;
32 import static org.apache.commons.collections.MapUtils.isNotEmpty;
33 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
34 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
35 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.EnumMap;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.ListIterator;
46 import java.util.Map.Entry;
47 import java.util.Optional;
49 import java.util.function.Function;
50 import java.util.regex.Pattern;
52 import fj.data.Either;
53 import org.apache.commons.codec.binary.Base64;
54 import org.apache.commons.collections.CollectionUtils;
55 import org.apache.commons.collections.MapUtils;
56 import org.apache.commons.collections4.ListUtils;
57 import org.apache.commons.lang.StringUtils;
58 import org.apache.commons.lang3.tuple.ImmutablePair;
59 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
60 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
61 import org.openecomp.sdc.be.components.csar.CsarInfo;
62 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
63 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
64 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
65 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
66 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
67 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
68 import org.openecomp.sdc.be.components.impl.utils.CINodeFilterUtils;
69 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
70 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
71 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
72 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
73 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
74 import org.openecomp.sdc.be.config.BeEcompErrorManager;
75 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
76 import org.openecomp.sdc.be.config.ConfigurationManager;
77 import org.openecomp.sdc.be.dao.api.ActionStatus;
78 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
79 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
80 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
81 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
82 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
83 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
84 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
85 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
86 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
87 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
88 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
89 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
90 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
91 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
92 import org.openecomp.sdc.be.impl.ComponentsUtils;
93 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
94 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
95 import org.openecomp.sdc.be.model.ArtifactDefinition;
96 import org.openecomp.sdc.be.model.CapabilityDefinition;
97 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
98 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
99 import org.openecomp.sdc.be.model.Component;
100 import org.openecomp.sdc.be.model.ComponentInstance;
101 import org.openecomp.sdc.be.model.ComponentInstanceInput;
102 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
103 import org.openecomp.sdc.be.model.ComponentParametersView;
104 import org.openecomp.sdc.be.model.DataTypeDefinition;
105 import org.openecomp.sdc.be.model.GroupDefinition;
106 import org.openecomp.sdc.be.model.InputDefinition;
107 import org.openecomp.sdc.be.model.InterfaceDefinition;
108 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
109 import org.openecomp.sdc.be.model.LifecycleStateEnum;
110 import org.openecomp.sdc.be.model.NodeTypeInfo;
111 import org.openecomp.sdc.be.model.Operation;
112 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
113 import org.openecomp.sdc.be.model.PropertyDefinition;
114 import org.openecomp.sdc.be.model.RelationshipImpl;
115 import org.openecomp.sdc.be.model.RelationshipInfo;
116 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
117 import org.openecomp.sdc.be.model.RequirementDefinition;
118 import org.openecomp.sdc.be.model.Resource;
119 import org.openecomp.sdc.be.model.UploadCapInfo;
120 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
121 import org.openecomp.sdc.be.model.UploadInfo;
122 import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
123 import org.openecomp.sdc.be.model.UploadPropInfo;
124 import org.openecomp.sdc.be.model.UploadReqInfo;
125 import org.openecomp.sdc.be.model.UploadResourceInfo;
126 import org.openecomp.sdc.be.model.User;
127 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
128 import org.openecomp.sdc.be.model.category.CategoryDefinition;
129 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
130 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
131 import org.openecomp.sdc.be.model.operations.StorageException;
132 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
133 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
134 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
135 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
136 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
137 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
138 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
139 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
140 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
141 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
142 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
143 import org.openecomp.sdc.be.tosca.CsarUtils;
144 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
145 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
146 import org.openecomp.sdc.be.user.IUserBusinessLogic;
147 import org.openecomp.sdc.be.user.UserBusinessLogic;
148 import org.openecomp.sdc.be.utils.CommonBeUtils;
149 import org.openecomp.sdc.be.utils.TypeUtils;
150 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
151 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
152 import org.openecomp.sdc.common.api.Constants;
153 import org.openecomp.sdc.common.datastructure.Wrapper;
154 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
155 import org.openecomp.sdc.common.log.wrappers.Logger;
156 import org.openecomp.sdc.common.util.GeneralUtility;
157 import org.openecomp.sdc.common.util.ValidationUtils;
158 import org.openecomp.sdc.exception.ResponseFormat;
159 import org.springframework.beans.factory.annotation.Autowired;
160 import org.springframework.web.context.WebApplicationContext;
161 import org.yaml.snakeyaml.DumperOptions;
162 import org.yaml.snakeyaml.Yaml;
164 import javax.servlet.ServletContext;
166 @org.springframework.stereotype.Component("resourceBusinessLogic")
167 public class ResourceBusinessLogic extends ComponentBusinessLogic {
169 private static final String DELETE_RESOURCE = "Delete Resource";
170 private static final String IN_RESOURCE = " in resource {} ";
171 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
172 public static final String INITIAL_VERSION = "0.1";
173 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
174 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
175 private static final String CREATE_RESOURCE = "Create Resource";
176 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
177 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
178 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
179 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
180 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
184 private ICapabilityTypeOperation capabilityTypeOperation = null;
187 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
190 private LifecycleBusinessLogic lifecycleBusinessLogic;
193 private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
196 private ResourceImportManager resourceImportManager;
199 private InputsBusinessLogic inputsBusinessLogic;
202 private CompositionBusinessLogic compositionBusinessLogic;
205 private ICacheMangerOperation cacheManagerOperation;
208 private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
211 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
214 private MergeInstanceUtils mergeInstanceUtils;
217 private UiComponentDataConverter uiComponentDataConverter;
220 private CsarBusinessLogic csarBusinessLogic;
223 * Default constructor
225 public ResourceBusinessLogic() {
226 log.debug("ResourceBusinessLogic started");
229 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
230 return lifecycleBusinessLogic;
233 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
234 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
237 public IElementOperation getElementDao() {
241 public void setElementDao(IElementOperation elementDao) {
242 this.elementDao = elementDao;
245 public IUserBusinessLogic getUserAdmin() {
246 return this.userAdmin;
249 public void setUserAdmin(UserBusinessLogic userAdmin) {
250 this.userAdmin = userAdmin;
253 public ComponentsUtils getComponentsUtils() {
254 return this.componentsUtils;
257 public void setComponentsUtils(ComponentsUtils componentsUtils) {
258 this.componentsUtils = componentsUtils;
261 public ArtifactsBusinessLogic getArtifactsManager() {
262 return artifactsBusinessLogic;
265 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
266 this.artifactsBusinessLogic = artifactsManager;
269 public ApplicationDataTypeCache getApplicationDataTypeCache() {
270 return applicationDataTypeCache;
273 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
274 this.applicationDataTypeCache = applicationDataTypeCache;
277 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
278 this.interfaceTypeOperation = interfaceTypeOperation;
282 * the method returns a list of all the resources that are certified, the
283 * returned resources are only abstract or only none abstract according to
290 public List<Resource> getAllCertifiedResources(boolean getAbstract,
291 HighestFilterEnum highestFilter, String userId) {
292 User user = validateUserExists(userId, "get All Certified Resources", false);
293 Boolean isHighest = null;
294 switch (highestFilter) {
300 case NON_HIGHEST_ONLY:
306 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
307 .getAllCertifiedResources(getAbstract, isHighest);
309 if (getResponse.isRight()) {
310 throw new StorageException(getResponse.right().value());
313 return getResponse.left().value();
316 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
317 ResourceTypeEnum resourceTypeEnum, String userId) {
319 validateUserExists(userId, "validate Resource Name Exists", false);
321 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
322 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
326 if (dataModelResponse.isLeft()) {
327 Map<String, Boolean> result = new HashMap<>();
328 result.put("isValid", dataModelResponse.left().value());
329 log.debug("validation was successfully performed.");
330 return Either.left(result);
333 ResponseFormat responseFormat = componentsUtils
334 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
336 return Either.right(responseFormat);
339 public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
340 User user, Map<String, byte[]> csarUIPayload, String payloadName) {
341 validateResourceBeforeCreate(resource, user, false);
342 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
343 if (StringUtils.isNotEmpty(csarUUID)) {
344 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
345 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
346 return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
349 return createResourceByDao(resource, user, auditingAction, false, false);
352 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
353 Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
354 String csarUUID = payloadName;
355 String csarVersion = null;
356 Resource updatedResource = null;
357 if (payloadName == null) {
358 csarUUID = resource.getCsarUUID();
359 csarVersion = resource.getCsarVersion();
361 if (csarUUID != null && !csarUUID.isEmpty()) {
362 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
363 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
364 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
365 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
366 overrideImmutableMetadata(oldResource, resource);
368 validateResourceBeforeCreate(resource, user, false);
369 String oldCsarVersion = oldResource.getCsarVersion();
370 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
372 // (on boarding flow): If the update includes same csarUUID and
373 // same csarVersion as already in the VF - no need to import the
374 // csar (do only metadata changes if there are).
375 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
376 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
379 updatedResource = updateResourceFromCsar(oldResource, resource, user,
380 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
383 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
384 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
386 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
387 throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
389 return updatedResource;
392 private void validateCsarIsNotAlreadyUsed(Resource oldResource,
393 Resource resource, String csarUUID, User user) {
394 // (on boarding flow): If the update includes a csarUUID: verify this
395 // csarUUID is not in use by another VF, If it is - use same error as
397 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
398 // select another or update the existing VF." %1 - csarUUID, %2 - VF
400 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
401 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
402 if (resourceLinkedToCsarRes.isRight()) {
403 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
404 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
405 resource.getSystemName());
406 throw new StorageException(resourceLinkedToCsarRes.right().value());
408 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
409 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
410 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
411 resourceLinkedToCsarRes.left().value().getName());
412 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
413 throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
414 resourceLinkedToCsarRes.left().value().getName());
418 private void validateCsarUuidMatching(Resource resource,
419 Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
420 // (on boarding flow): If the update includes csarUUID which is
421 // different from the csarUUID of the VF - fail with
422 // error: "Error: Resource %1 cannot be updated using since it is linked
423 // to a different VSP" %1 - VF name
424 String oldCsarUUID = oldResource.getCsarUUID();
425 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
427 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
428 resourceUniqueId, csarUUID, oldCsarUUID);
429 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
430 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
431 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
432 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
436 private Resource getResourceByUniqueId(String resourceUniqueId) {
437 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
438 if (oldResourceRes.isRight()) {
439 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
440 oldResourceRes.right().value());
441 throw new StorageException(oldResourceRes.right().value());
443 return oldResourceRes.left().value();
446 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
447 resource.setName(oldRresource.getName());
448 resource.setIcon(oldRresource.getIcon());
449 resource.setTags(oldRresource.getTags());
450 resource.setCategories(oldRresource.getCategories());
451 resource.setDerivedFrom(oldRresource.getDerivedFrom());
454 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
455 User user, AuditingActionEnum updateResource, boolean inTransaction,
456 Map<String, byte[]> csarUIPayload, String csarUUID) {
457 Resource updatedResource = null;
458 validateLifecycleState(oldResource, user);
459 String lockedResourceId = oldResource.getUniqueId();
460 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
461 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
462 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
463 "update Resource From Csar");
464 if (lockResult.isRight()) {
465 throw new ByResponseFormatComponentException(lockResult.right().value());
468 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
470 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
471 nodeTypesInfo, csarInfo, oldResource);
472 if (findNodeTypesArtifactsToHandleRes.isRight()) {
473 log.debug("failed to find node types for update with artifacts during import csar {}. ",
474 csarInfo.getCsarUUID());
475 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
477 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
480 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
481 csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
483 connectUiRelations(oldResource, updatedResource);
485 } catch (ComponentException|StorageException e){
486 rollback(inTransaction, newResource, createdArtifacts, null);
491 log.debug("unlock resource {}", lockedResourceId);
492 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
494 return updatedResource;
498 private void validateLifecycleState(Resource oldResource, User user) {
499 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
500 !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
501 log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
502 oldResource.getLastUpdaterUserId(), user.getUserId());
503 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
507 private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
508 Either<Resource, ResponseFormat> result;
510 List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
512 StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
513 if (status == StorageOperationStatus.OK) {
514 newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
515 result = Either.left(newResource);
517 result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
523 private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
524 AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
525 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
526 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
527 String nodeName, boolean isNested) {
528 boolean inTransaction = true;
529 boolean shouldLock = false;
530 Resource preparedResource = null;
531 ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
533 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
534 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
535 if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
536 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
538 preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
539 inTransaction, shouldLock, isNested).left;
540 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
541 handleResourceGenericType(preparedResource);
542 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
543 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
544 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
545 preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
546 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
547 } catch (ByResponseFormatComponentException e) {
548 ResponseFormat responseFormat = e.getResponseFormat();
549 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
550 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
552 } catch (ByActionStatusComponentException e) {
553 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
554 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
555 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
557 } catch (StorageException e){
558 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
559 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
560 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
563 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
564 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
565 preparedResource.getSystemName());
566 if (validateUpdateVfGroupNamesRes.isRight()) {
568 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
570 // add groups to resource
571 Map<String, GroupDefinition> groups;
573 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
574 groups = validateUpdateVfGroupNamesRes.left().value();
576 groups = uploadComponentInstanceInfoMap.getGroups();
578 handleGroupsProperties(preparedResource, groups);
579 preparedResource = updateGroupsOnResource(preparedResource, groups);
580 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
581 nodeTypesArtifactsToHandle);
583 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
584 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
585 if (updateArtifactsEither.isRight()) {
586 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
587 throw new ByResponseFormatComponentException(updateArtifactsEither.right().value());
589 preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
591 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
592 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
593 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
595 throw new ByResponseFormatComponentException(responseFormat);
597 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
598 return preparedResource;
601 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
602 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
603 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
605 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
606 Resource resource = preparedResource;
608 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
609 .getNodeTypesArtifactsToHandle();
610 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
611 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
612 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
613 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
614 if (handleNodeTypeArtifactsRes.isRight()) {
615 return Either.right(handleNodeTypeArtifactsRes.right().value());
619 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
620 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
621 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
622 if (createdCsarArtifactsEither.isRight()) {
623 return createdCsarArtifactsEither;
626 resource = createdCsarArtifactsEither.left().value();
628 return Either.left(resource);
631 private Resource handleResourceGenericType(Resource resource) {
632 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
633 if (resource.shouldGenerateInputs()) {
634 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
636 return genericResource;
639 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
640 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
642 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
643 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
644 = Either.left(nodeTypesArtifactsToHandle);
647 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
648 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
649 extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
650 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
651 oldResource.getName(), csarInfo.getCsarUUID());
652 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
653 extractedVfcsArtifacts,
654 namespace, vfcToscaNames));
655 } catch (Exception e) {
656 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
657 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
658 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
660 return nodeTypesArtifactsToHandleRes;
663 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
664 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
666 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
667 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
668 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
669 if (!isEmpty(extractedVfcsArtifacts)) {
670 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
671 if (extractedVfcsArtifacts.containsKey(namespace)) {
672 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
674 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
675 } else if (curNodeType != null) {
676 // delete all artifacts if have not received artifacts from
678 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
679 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
680 // delete all informational artifacts
681 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
682 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
684 // delete all deployment artifacts
685 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
686 if (!artifactsToDelete.isEmpty()) {
687 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
690 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
691 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
695 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
696 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
697 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
698 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
699 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
700 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
701 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
702 return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
704 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
709 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
710 Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
712 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
714 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
715 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
716 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
717 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
718 collectExistingArtifacts(curNodeType));
719 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
720 } catch (Exception e) {
721 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
722 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
724 return nodeTypeArtifactsToHandle;
727 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
728 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
729 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
730 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
731 if (!artifactsToUpload.isEmpty()) {
732 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
734 if (!artifactsToUpdate.isEmpty()) {
735 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
737 if (!artifactsToDelete.isEmpty()) {
738 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
741 return nodeTypeArtifactsToHandle;
744 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
745 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
746 Map<String, ArtifactDefinition> existingArtifacts) {
747 if (!existingArtifacts.isEmpty()) {
748 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
749 artifactsToDelete.addAll(existingArtifacts.values());
753 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
754 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
756 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
758 if (foundArtifact.isPresent()) {
759 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
760 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
761 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
762 artifactsToUpload.remove(currNewArtifact);
764 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
765 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
766 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
767 foundArtifact.get().getArtifactType());
772 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
773 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
774 foundArtifact.setPayload(currNewArtifact.getPayloadData());
775 foundArtifact.setPayloadData(
776 Base64.encodeBase64String(currNewArtifact.getPayloadData()));
777 foundArtifact.setArtifactChecksum(GeneralUtility
778 .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
779 artifactsToUpdate.add(foundArtifact);
783 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
784 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
785 if (curNodeType == null) {
786 return existingArtifacts;
788 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
789 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
791 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
793 .putAll(curNodeType.getArtifacts().entrySet()
795 .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
796 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
798 return existingArtifacts;
802 * Changes resource life cycle state to checked out
806 * @param inTransaction
809 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
810 Either<Resource, ResponseFormat> checkoutResourceRes;
812 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
813 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
815 "************* Going to change life cycle state of resource {} to not certified checked out. ",
817 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
818 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
819 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
820 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
821 inTransaction, true);
822 if (checkoutRes.isRight()) {
823 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
824 resource.getComponentType().getNodeType(), resource.getUniqueId(),
825 checkoutRes.right().value().getStatus());
826 checkoutResourceRes = Either.right(checkoutRes.right().value());
828 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
831 checkoutResourceRes = Either.left(resource);
833 } catch (Exception e) {
834 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
835 checkoutResourceRes = Either.right(responseFormat);
836 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
839 return checkoutResourceRes;
843 * Handles Artifacts of NodeType
845 * @param nodeTypeResource
846 * @param nodeTypeArtifactsToHandle
848 * @param inTransaction
851 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
852 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
853 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
854 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
855 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
856 Either<Resource, ResponseFormat> changeStateResponse;
858 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
859 if (changeStateResponse.isRight()) {
860 return Either.right(changeStateResponse.right().value());
862 nodeTypeResource = changeStateResponse.left().value();
864 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
865 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
866 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
868 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
869 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
870 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
871 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
872 nodeTypeResource.getName());
873 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
874 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
875 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
876 ignoreLifecycleState, curOperation),
877 false, inTransaction);
878 if (handleNodeTypeArtifactsRequestRes.isRight()) {
879 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
882 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
883 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
885 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
888 if (handleNodeTypeArtifactsRes == null) {
889 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
891 } catch (Exception e) {
892 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
893 handleNodeTypeArtifactsRes = Either.right(responseFormat);
894 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
896 return handleNodeTypeArtifactsRes;
899 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
900 String vfResourceName, CsarInfo csarInfo) {
901 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
903 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
904 if (!nodes.isEmpty()) {
905 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
906 while (nodesNameEntry.hasNext()) {
907 Entry<String, Object> nodeType = nodesNameEntry.next();
908 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
909 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
910 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
913 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
914 vfcToscaNames.put(cvfc.getType(),
915 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
917 return vfcToscaNames;
920 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
921 Map<String, Object> nodes = new HashMap<>();
922 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
923 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
925 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
929 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
930 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
931 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
932 if (eitherNodeTypes.isLeft()) {
933 nodes.putAll(eitherNodeTypes.left().value());
937 public Resource createResourceFromCsar(Resource resource, User user,
938 Map<String, byte[]> csarUIPayload, String csarUUID) {
939 log.trace("************* created successfully from YAML, resource TOSCA ");
941 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
943 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
944 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
945 nodeTypesInfo, csarInfo, resource);
946 if (findNodeTypesArtifactsToHandleRes.isRight()) {
947 log.debug("failed to find node types for update with artifacts during import csar {}. ",
948 csarInfo.getCsarUUID());
949 throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
951 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
952 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
954 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
955 vfResource.getToscaResourceName());
959 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
960 log.trace("validating resource before create");
961 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
962 // validate user role
963 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
964 // VF / PNF "derivedFrom" should be null (or ignored)
965 if (ModelConverter.isAtomicComponent(resource)) {
966 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
968 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
972 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
973 // nodeTypesArtifactsToCreate, true, false, null
974 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
975 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
976 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
977 boolean shouldLock, boolean inTransaction, String nodeName) {
979 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
980 Resource createdResource;
982 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
983 if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
984 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
986 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
987 createdResource = createResourceAndRIsFromYaml(yamlName, resource,
988 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
989 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
990 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
991 } catch (ByActionStatusComponentException e) {
992 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
993 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
995 } catch (ByResponseFormatComponentException e) {
996 ResponseFormat responseFormat = e.getResponseFormat();
997 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
999 } catch (StorageException e){
1000 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1001 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1004 return createdResource;
1008 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
1009 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1010 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1011 CsarInfo csarInfo) {
1013 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
1014 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
1015 if (toscaVersion.isRight()) {
1016 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
1018 Map<String, Object> mapToConvert = new HashMap<>();
1019 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
1020 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
1021 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
1022 return csarInfo.getCreatedNodes();
1025 private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
1026 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
1027 .left().orValue(HashMap::new);
1030 private void createNodeTypes(String yamlName, Resource resource, boolean needLock, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
1031 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
1032 Resource vfcCreated = null;
1033 while (nodesNameValueIter.hasNext()) {
1034 Entry<String, Object> nodeType = nodesNameValueIter.next();
1035 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1036 || nodeTypesArtifactsToHandle.isEmpty() ? null
1037 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1039 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1040 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1041 vfcCreated = handleNestedVfc(resource,
1042 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1044 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1045 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1046 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
1047 log.trace("************* Going to create node {}", nodeType.getKey());
1048 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
1049 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
1051 log.debug("************* Finished to create node {}", nodeType.getKey());
1053 vfcCreated = resourceCreated.getLeft();
1054 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
1055 vfcCreated.getToscaResourceName());
1057 if (vfcCreated != null) {
1058 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1060 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1064 private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1065 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1068 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1069 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1071 log.debug("************* Going to create node types from yaml {}", yamlName);
1072 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
1073 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1074 log.debug("************* Finished to create node types from yaml {}", yamlName);
1076 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1077 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1078 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1079 csarInfo, nodeName, yamlName);
1084 private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1085 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1086 String nodeName, String yamlName) {
1088 Resource oldComplexVfc = null;
1089 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1090 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1091 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1092 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1093 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1094 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1095 nodeName).getRight());
1097 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1098 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1099 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1100 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1101 } else if (oldComplexVfcRes.isLeft()) {
1102 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1103 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1104 oldComplexVfcRes.left().value(), newComplexVfc,
1105 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1106 if (eitherValidation.isLeft()) {
1107 oldComplexVfc = oldComplexVfcRes.left().value();
1110 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1111 oldComplexVfc, newComplexVfc);
1112 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1113 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1114 CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1115 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1116 Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1118 if (result.isRight()) {
1119 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1121 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1122 csarInfo.removeNodeFromQueue();
1123 return result.left().value();
1126 private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1127 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1128 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1130 Resource handleComplexVfcRes;
1131 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1132 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1133 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1134 .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
1135 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1136 if (oldComplexVfc == null) {
1137 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1138 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1140 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1141 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1142 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1144 return handleComplexVfcRes;
1147 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1148 Map<String, NodeTypeInfo> nodesInfo) {
1150 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1151 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1152 csarInfo.addNodeToQueue(nodeName);
1153 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1154 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1157 private String getNodeTypeActualName(String fullName) {
1158 String nameWithouNamespacePrefix = fullName
1159 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1160 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1161 String resourceType = findTypes[0];
1162 return nameWithouNamespacePrefix.substring(resourceType.length());
1165 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1166 String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1167 Resource resourceVf, boolean needLock,
1168 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1169 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1172 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1174 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1175 resourceMetaData.getResourceType(), csarInfo);
1176 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1177 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1178 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1179 nodeNameValue.getKey(), isNested);
1182 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1183 String nodeResourceType, CsarInfo csarInfo) {
1184 // We need to create a Yaml from each node_types in order to create
1185 // resource from each node type using import normative flow.
1186 DumperOptions options = new DumperOptions();
1187 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1188 Yaml yaml = new Yaml(options);
1190 Map<String, Object> node = new HashMap<>();
1191 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1192 .getLeft(), nodeNameValue.getValue());
1193 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1195 return yaml.dumpAsMap(mapToConvert);
1198 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1199 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1200 return Either.left(true);
1203 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1204 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1205 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1206 String nodeName, boolean isNested) {
1208 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1209 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1210 Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1211 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1212 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1213 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
1214 .left().on(this::failOnCertification);
1217 private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
1218 throw new ByResponseFormatComponentException(error);
1221 private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1222 String nodeName, User user) {
1223 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1225 // validate nodetype name prefix
1226 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1227 log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1228 Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1229 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1230 yamlName, resourceMetaData.getName(), nodeName);
1233 String actualName = this.getNodeTypeActualName(nodeName);
1234 String namePrefix = nodeName.replace(actualName, "");
1235 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1237 // if we import from csar, the node_type name can be
1238 // org.openecomp.resource.abstract.node_name - in this case we always
1240 if (resourceType.equals(Constants.ABSTRACT)) {
1241 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1244 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1245 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1246 ResourceTypeEnum.values());
1247 throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1248 yamlName, resourceMetaData.getName(), nodeName);
1252 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1254 // Setting type from name
1255 String type = resourceType.toUpperCase();
1256 resourceMetaData.setResourceType(type);
1258 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1259 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1260 resourceMetaData.setContactId(user.getUserId());
1261 resourceMetaData.setVendorName(resourceVf.getVendorName());
1262 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1265 List<String> tags = new ArrayList<>();
1266 tags.add(resourceMetaData.getName());
1267 resourceMetaData.setTags(tags);
1270 CategoryDefinition category = new CategoryDefinition();
1271 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1272 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1273 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1274 category.addSubCategory(subCategory);
1275 List<CategoryDefinition> categories = new ArrayList<>();
1276 categories.add(category);
1277 resourceMetaData.setCategories(categories);
1279 return resourceMetaData;
1282 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1283 Map<String, NodeTypeInfo> nodesInfo) {
1284 Resource cvfc = new Resource();
1285 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1286 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1287 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1288 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1289 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1290 cvfc.setAbstract(true);
1291 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1292 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1293 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1294 cvfc.setContactId(csarInfo.getModifier().getUserId());
1295 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1296 cvfc.setVendorName(resourceVf.getVendorName());
1297 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1298 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1299 cvfc.setToscaResourceName(
1300 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1302 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1304 List<String> tags = new ArrayList<>();
1305 tags.add(cvfc.getName());
1308 CategoryDefinition category = new CategoryDefinition();
1309 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1310 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1311 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1312 category.addSubCategory(subCategory);
1313 List<CategoryDefinition> categories = new ArrayList<>();
1314 categories.add(category);
1315 cvfc.setCategories(categories);
1317 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1318 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1319 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1324 private String buildCvfcName(String resourceVfName, String nodeName) {
1325 String nameWithouNamespacePrefix = nodeName
1326 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1327 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1328 String resourceType = findTypes[0];
1329 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1330 return addCvfcSuffixToResourceName(resourceName);
1333 private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
1334 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1335 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1336 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1337 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1338 boolean shouldLock, boolean inTransaction, String nodeName) {
1340 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1343 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1345 if (lockResult.isRight()) {
1346 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1347 throw new ByResponseFormatComponentException(lockResult.right().value());
1349 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1352 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1353 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1354 resource = createResourceTransaction(resource,
1355 csarInfo.getModifier(), isNormative);
1356 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1357 log.trace("************* Going to add inputs from yaml {}", yamlName);
1358 if (resource.shouldGenerateInputs())
1359 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1361 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1362 resource = createInputsOnResource(resource, inputs);
1363 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1365 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1367 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1369 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1370 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1371 nodeTypesArtifactsToCreate, nodeName);
1372 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1373 // validate update vf module group names
1374 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1375 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1376 if (validateUpdateVfGroupNamesRes.isRight()) {
1377 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1378 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
1380 // add groups to resource
1381 Map<String, GroupDefinition> groups;
1382 log.trace("************* Going to add groups from yaml {}", yamlName);
1384 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1385 groups = validateUpdateVfGroupNamesRes.left().value();
1387 groups = parsedToscaYamlInfo.getGroups();
1390 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1392 if (createGroupsOnResource.isRight()) {
1393 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1394 throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
1396 resource = createGroupsOnResource.left().value();
1397 log.trace("************* Finished to add groups from yaml {}", yamlName);
1399 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1401 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1402 nodeTypesArtifactsToCreate);
1404 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1405 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1406 if (createArtifactsEither.isRight()) {
1407 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1408 throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
1411 resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
1413 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1414 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1415 ASDCKpiApi.countCreatedResourcesKPI();
1418 } catch(ComponentException|StorageException e) {
1419 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1422 if (!inTransaction) {
1426 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1427 NodeTypeEnum.Resource);
1432 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1433 if(!inTransaction) {
1434 titanDao.rollback();
1436 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1437 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1438 log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
1442 private Resource getResourceWithGroups(String resourceId) {
1444 ComponentParametersView filter = new ComponentParametersView();
1445 filter.setIgnoreGroups(false);
1446 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
1447 if (updatedResource.isRight()) {
1448 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
1450 return updatedResource.left().value();
1453 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1454 Map<String, GroupDefinition> groups) {
1455 if (groups != null && !groups.isEmpty()) {
1456 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
1458 handleGroupsProperties(resource, groups);
1459 fillGroupsFinalFields(groupsAsList);
1460 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1461 groupsAsList, true);
1462 if (createGroups.isRight()) {
1463 return Either.right(createGroups.right().value());
1466 return Either.left(resource);
1468 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1469 .getToscaElement(resource.getUniqueId());
1470 if (updatedResource.isRight()) {
1471 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1472 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1473 return Either.right(responseFormat);
1475 return Either.left(updatedResource.left().value());
1478 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1479 List<InputDefinition> inputs = resource.getInputs();
1480 if (MapUtils.isNotEmpty(groups)) {
1483 .filter(g -> isNotEmpty(g.getProperties()))
1484 .flatMap(g -> g.getProperties().stream())
1485 .forEach(p -> handleGetInputs(p, inputs));
1489 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1490 if (isNotEmpty(property.getGetInputValues())) {
1491 if (inputs == null || inputs.isEmpty()) {
1492 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1493 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1495 .map(GetInputValueDataDefinition::getInputName)
1496 .collect(toList()).toString());
1498 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1499 while (getInputValuesIter.hasNext()) {
1500 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1501 InputDefinition input = findInputByName(inputs, getInput);
1502 getInput.setInputId(input.getUniqueId());
1503 if (getInput.getGetInputIndex() != null) {
1504 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1505 input = findInputByName(inputs, getInputIndex);
1506 getInputIndex.setInputId(input.getUniqueId());
1507 getInputValuesIter.add(getInputIndex);
1513 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1514 Optional<InputDefinition> inputOpt = inputs.stream()
1515 .filter(p -> p.getName().equals(getInput.getInputName()))
1517 if (!inputOpt.isPresent()) {
1518 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1519 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1521 return inputOpt.get();
1524 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1525 groupsAsList.forEach(groupDefinition -> {
1526 groupDefinition.setInvariantName(groupDefinition.getName());
1527 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1531 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1532 if (isEmpty(groups)) {
1535 updateOrCreateGroups(resource, groups);
1537 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1538 .getToscaElement(resource.getUniqueId());
1539 if (updatedResource.isRight()) {
1540 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
1541 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1543 return updatedResource.left().value();
1546 private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1547 List<GroupDefinition> groupsFromResource = resource.getGroups();
1548 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1549 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1550 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1551 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1552 if (isNotEmpty(groupsFromResource)) {
1553 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1554 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1556 groupsToCreate.addAll(groupsAsList);
1558 if (isNotEmpty(groupsToCreate)) {
1559 fillGroupsFinalFields(groupsToCreate);
1560 if (isNotEmpty(groupsFromResource)) {
1561 groupBusinessLogic.addGroups(resource,
1562 groupsToCreate, true)
1564 .on(this::throwComponentException);
1566 groupBusinessLogic.createGroups(resource,
1567 groupsToCreate, true)
1569 .on(this::throwComponentException);
1572 if (isNotEmpty(groupsToDelete)) {
1573 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1575 .on(this::throwComponentException);
1577 if (isNotEmpty(groupsToUpdate)) {
1578 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1580 .on(this::throwComponentException);
1584 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1585 for (GroupDefinition group : groupsFromResource) {
1586 Optional<GroupDefinition> op = groupsAsList.stream()
1587 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1588 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1589 groupsToDelete.add(group);
1594 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1595 for (GroupDefinition group : groupsAsList) {
1596 Optional<GroupDefinition> op = groupsFromResource.stream()
1597 .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1598 if (op.isPresent()) {
1599 GroupDefinition groupToUpdate = op.get();
1600 groupToUpdate.setMembers(group.getMembers());
1601 groupToUpdate.setCapabilities(group.getCapabilities());
1602 groupToUpdate.setProperties(group.getProperties());
1603 groupsToUpdate.add(groupToUpdate);
1605 groupsToCreate.add(group);
1610 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1611 List<InputDefinition> resourceProperties = resource.getInputs();
1612 if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1614 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1616 if (createInputs.isRight()) {
1617 throw new ByResponseFormatComponentException(createInputs.right().value());
1622 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1623 .getToscaElement(resource.getUniqueId());
1624 if (updatedResource.isRight()) {
1625 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
1626 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1628 return updatedResource.left().value();
1631 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1633 List<GroupDefinition> result = new ArrayList<>();
1634 List<ComponentInstance> componentInstances = component.getComponentInstances();
1636 if (groups != null) {
1637 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1638 if (validateCyclicGroupsDependencies.isRight()) {
1639 throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
1641 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1642 String groupName = entry.getKey();
1643 GroupDefinition groupDefinition = entry.getValue();
1644 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1645 updatedGroupDefinition.setMembers(null);
1646 Map<String, String> members = groupDefinition.getMembers();
1647 if (members != null) {
1648 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1650 result.add(updatedGroupDefinition);
1656 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1657 Set<String> compInstancesNames = members.keySet();
1659 if (CollectionUtils.isEmpty(componentInstances)) {
1660 String membersAstString = compInstancesNames.stream().collect(joining(","));
1661 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1662 membersAstString, groupName, component.getNormalizedName());
1663 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
1664 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1665 component.getNormalizedName(), getComponentTypeForResponse(component)));
1667 // Find all component instances with the member names
1668 Map<String, String> memberNames = componentInstances.stream()
1669 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1670 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1671 Map<String, String> relevantInstances = memberNames.entrySet().stream()
1672 .filter(n -> compInstancesNames.contains(n.getKey()))
1673 .collect(toMap(Entry::getKey, Entry::getValue));
1675 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1677 List<String> foundMembers = new ArrayList<>();
1678 if (relevantInstances != null) {
1679 foundMembers = relevantInstances.keySet().stream().collect(toList());
1681 compInstancesNames.removeAll(foundMembers);
1682 String membersAstString = compInstancesNames.stream().collect(joining(","));
1683 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1684 groupName, component.getNormalizedName());
1685 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
1686 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1687 component.getNormalizedName(), getComponentTypeForResponse(component)));
1689 updatedGroupDefinition.setMembers(relevantInstances);
1693 * This Method validates that there is no cyclic group dependencies. meaning
1694 * group A as member in group B which is member in group A
1699 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1701 Either<Boolean, ResponseFormat> result = Either.left(true);
1703 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1704 while (allGroupsItr.hasNext() && result.isLeft()) {
1705 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1706 // Fetches a group member A
1707 String groupAName = groupAEntry.getKey();
1708 // Finds all group members in group A
1709 Set<String> allGroupAMembersNames = new HashSet<>();
1710 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1711 // If A is a group member of itself found cyclic dependency
1712 if (allGroupAMembersNames.contains(groupAName)) {
1713 ResponseFormat responseFormat = componentsUtils
1714 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1715 result = Either.right(responseFormat);
1718 } catch (Exception e) {
1719 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1720 result = Either.right(responseFormat);
1721 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1727 * This Method fills recursively the set groupMembers with all the members
1728 * of the given group which are also of type group.
1732 * @param allGroupMembers
1735 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1736 Set<String> allGroupMembers) {
1738 // Found Cyclic dependency
1739 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1742 GroupDefinition groupDefinition = allGroups.get(groupName);
1743 // All Members Of Current Group Resource Instances & Other Groups
1744 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1745 // Filtered Members Of Current Group containing only members which
1747 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1748 // Keep Only Elements of type group and not Resource Instances
1749 filter(allGroups::containsKey).
1750 // Add Filtered Elements to main Set
1751 peek(allGroupMembers::add).
1755 // Recursively call the method for all the filtered group members
1756 for (String innerGroupName : currGroupFilteredMembers) {
1757 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1762 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
1763 Set<String> allGroupMembers) {
1765 boolean stop = false;
1766 // In Case Not Group Stop
1767 if (!allGroups.containsKey(groupName)) {
1770 // In Case Group Has no members stop
1772 GroupDefinition groupDefinition = allGroups.get(groupName);
1773 stop = isEmpty(groupDefinition.getMembers());
1776 // In Case all group members already contained stop
1778 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1779 Set<String> membersOfTypeGroup = allMembers.stream().
1780 // Filter In Only Group members
1781 filter(allGroups::containsKey).
1784 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1789 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1790 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1791 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1792 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1793 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1796 log.debug("************* Going to create all nodes {}", yamlName);
1797 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1798 nodeTypesInfo, csarInfo, nodeName);
1799 log.debug("************* Finished to create all nodes {}", yamlName);
1800 log.debug("************* Going to create all resource instances {}", yamlName);
1801 resource = createResourceInstances(yamlName, resource,
1802 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1803 log.debug("************* Finished to create all resource instances {}", yamlName);
1804 log.debug("************* Going to create all relations {}", yamlName);
1805 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1806 log.debug("************* Finished to create all relations {}", yamlName);
1807 log.debug("************* Going to create positions {}", yamlName);
1808 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1809 log.debug("************* Finished to set positions {}", yamlName);
1813 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
1814 List<ArtifactDefinition> artifactsToAdd) {
1815 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
1817 artifactsToAdd.stream().forEach(a -> {
1818 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1819 vfcArtifacts.add(a);
1821 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1827 @SuppressWarnings("unchecked")
1828 private void handleNodeTypes(String yamlName, Resource resource,
1829 String topologyTemplateYaml, boolean needLock,
1830 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1831 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1832 CsarInfo csarInfo, String nodeName) {
1834 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1835 if (nodeTypeEntry.getValue().isNested()) {
1837 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1838 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1839 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1842 Map<String, Object> mappedToscaTemplate = null;
1843 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
1844 && nodeTypesInfo.containsKey(nodeName)) {
1845 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1847 if (isEmpty(mappedToscaTemplate)) {
1848 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1850 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1851 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1852 } catch(ByActionStatusComponentException e){
1853 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1854 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1856 } catch(ByResponseFormatComponentException e){
1857 ResponseFormat responseFormat = e.getResponseFormat();
1858 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1860 } catch (StorageException e){
1861 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1862 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1865 // add the created node types to the cache although they are not in the
1867 csarInfo.getCreatedNodes().values().stream()
1868 .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1871 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
1872 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1873 boolean inTransaction) {
1875 if (csarInfo.getCsar() != null) {
1876 String vendorLicenseModelId = null;
1877 String vfLicenseModelId = null;
1879 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1880 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1881 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1882 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1883 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1884 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1886 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1887 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1893 // Specific Behavior for license artifacts
1894 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1895 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
1896 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1897 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
1898 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
1900 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1901 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1902 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1903 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
1904 artifactOperation, null, true, shouldLock, inTransaction);
1906 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
1907 createdArtifacts, shouldLock, inTransaction, artifactOperation);
1908 if (eitherCreateResult.isRight()) {
1909 return Either.right(eitherCreateResult.right().value());
1911 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1912 .getToscaElement(resource.getUniqueId());
1913 if (eitherGerResource.isRight()) {
1914 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1915 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1917 return Either.right(responseFormat);
1920 resource = eitherGerResource.left().value();
1922 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1924 if (artifacsMetaCsarStatus.isLeft()) {
1925 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1926 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1927 Either<Resource, ResponseFormat> createArtifactsFromCsar;
1928 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1929 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1931 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1934 if (createArtifactsFromCsar.isRight()) {
1935 log.debug("Couldn't create artifacts from artifacts.meta");
1936 return Either.right(createArtifactsFromCsar.right().value());
1939 return Either.left(createArtifactsFromCsar.left().value());
1942 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
1946 return Either.left(resource);
1950 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
1951 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1952 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1953 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1954 boolean inTransaction) {
1955 byte[] artifactFileBytes = null;
1957 if (csarInfo.getCsar().containsKey(artifactPath)) {
1958 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1960 Either<Boolean, ResponseFormat> result = Either.left(true);
1961 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
1962 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1963 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
1964 shouldLock, inTransaction);
1965 if (handleDelete.isRight()) {
1966 result = Either.right(handleDelete.right().value());
1972 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1973 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1974 ArtifactOperationEnum.CREATE);
1978 if (artifactFileBytes != null) {
1979 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1980 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1981 artifactFileBytes, null, isFromCsar);
1982 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1983 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1984 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1985 if (eitherNonMetaArtifacts.isRight()) {
1986 BeEcompErrorManager.getInstance()
1987 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1988 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1989 ErrorSeverity.WARNING);
1990 return Either.right(eitherNonMetaArtifacts.right().value());
1996 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
1997 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2001 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2002 List<ArtifactDefinition> createdArtifacts,
2003 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2004 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
2005 && eitherNonMetaArtifacts.isLeft()) {
2006 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
2007 if (eitherResult.isLeft()) {
2008 createdArtifacts.add(eitherResult.left().value());
2014 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2015 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2016 ArtifactOperationInfo artifactOperation) {
2018 Either<Resource, ResponseFormat> resStatus = null;
2019 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2022 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
2023 if (artifactPathAndNameList.isRight()) {
2024 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2025 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
2027 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2029 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
2030 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2031 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
2033 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2034 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
2036 if (findVfCsarArtifactsToHandleRes.isRight()) {
2037 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2039 if (resStatus == null) {
2040 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2043 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2044 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
2046 if (resStatus == null) {
2047 resStatus = Either.left(resource);
2049 } catch (Exception e) {
2050 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2051 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2053 CsarUtils.handleWarningMessages(collectedWarningMessages);
2058 private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, Either<Resource, ResponseFormat> resStatus, EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
2059 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2062 Optional<ResponseFormat> optionalCreateInDBError =
2063 // Stream of artifacts to be created
2064 currArtifactOperationPair.getValue().stream()
2065 // create each artifact
2066 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2067 e.getArtifactName(), e.getArtifactType().getType(),
2068 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2069 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2070 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2071 currArtifactOperationPair.getKey()),
2072 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2073 // filter in only error
2074 .filter(Either::isRight).
2075 // Convert the error from either to
2077 map(e -> e.right().value()).
2078 // Check if an error occurred
2080 // Error found on artifact Creation
2081 if (optionalCreateInDBError.isPresent()) {
2082 resStatus = Either.right(optionalCreateInDBError.get());
2089 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
2090 List<NonMetaArtifactInfo> artifactPathAndNameList =
2091 // Stream of file paths contained in csar
2092 csarInfo.getCsar().entrySet().stream()
2093 // Filter in only VF artifact path location
2094 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2096 // Validate and add warnings
2097 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2098 collectedWarningMessages))
2099 // Filter in Non Warnings
2100 .filter(Either::isLeft)
2101 // Convert from Either to NonMetaArtifactInfo
2102 .map(e -> e.left().value())
2105 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2106 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2107 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2108 return Either.right(nonMetaArtifactInfo.getArtifactName());
2111 return Either.left(artifactPathAndNameList);
2114 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2115 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2117 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2118 // collect all Deployment and Informational artifacts of VF
2119 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2120 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2122 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2123 existingArtifacts.addAll(resource.getArtifacts().values());
2125 existingArtifacts = existingArtifacts.stream()
2126 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2127 // was created from HEAT.meta
2128 .filter(this::isNonMetaArtifact).collect(toList());
2130 List<String> artifactsToIgnore = new ArrayList<>();
2131 // collect IDs of Artifacts of VF which belongs to any group
2132 if (resource.getGroups() != null) {
2133 resource.getGroups().stream().forEach(g -> {
2134 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
2135 artifactsToIgnore.addAll(g.getArtifacts());
2139 existingArtifacts = existingArtifacts.stream()
2140 // filter artifacts which belongs to any group
2141 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
2142 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2145 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2146 boolean result = true;
2147 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2153 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2154 boolean result = true;
2155 if (artifact.getArtifactType() == null
2156 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2157 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2163 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
2164 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2165 log.debug("#createResourceInstancesRelations - Going to create relations ");
2166 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2167 if (((isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
2168 resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
2169 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
2170 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2171 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
2173 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2174 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2175 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2176 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2177 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2178 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2179 Map<String, Resource> originCompMap = new HashMap<>();
2180 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2181 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2183 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2184 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2185 if (allDataTypes.isRight()) {
2186 TitanOperationStatus status = allDataTypes.right().value();
2187 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2188 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2189 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2190 DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
2193 Resource finalResource = resource;
2194 uploadResInstancesMap
2196 .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2197 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
2198 instArtifacts, instAttributes, originCompMap, instInputs, i));
2200 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2201 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2202 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2203 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2204 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2205 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2207 resource = getResourceAfterCreateRelations(resource);
2209 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2210 associateResourceInstances(yamlName, resource, relations);
2211 handleSubstitutionMappings(resource, uploadResInstancesMap);
2212 log.debug("************* in create relations, getResource start");
2213 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2214 log.debug("************* in create relations, getResource end");
2215 if (eitherGetResource.isRight()) {
2216 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
2217 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
2219 return eitherGetResource.left().value();
2222 private Resource getResourceAfterCreateRelations(Resource resource) {
2223 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2224 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2225 .getToscaElement(resource.getUniqueId(), parametersView);
2227 if (eitherGetResource.isRight()) {
2228 throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2230 return eitherGetResource.left().value();
2233 private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2234 StorageOperationStatus addArtToInst;
2235 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2236 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2237 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2239 throw new ByResponseFormatComponentException(componentsUtils
2240 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2244 private ComponentParametersView getComponentFilterAfterCreateRelations() {
2245 ComponentParametersView parametersView = new ComponentParametersView();
2246 parametersView.disableAll();
2247 parametersView.setIgnoreComponentInstances(false);
2248 parametersView.setIgnoreComponentInstancesProperties(false);
2249 parametersView.setIgnoreCapabilities(false);
2250 parametersView.setIgnoreRequirements(false);
2251 parametersView.setIgnoreGroups(false);
2252 return parametersView;
2255 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
2256 StorageOperationStatus addArtToInst;
2257 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2258 resource.getUniqueId());
2259 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2260 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2262 throw new ByResponseFormatComponentException(componentsUtils
2263 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2267 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2268 StorageOperationStatus addArtToInst;
2269 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2270 resource.getUniqueId());
2271 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2272 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2274 throw new ByResponseFormatComponentException(componentsUtils
2275 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2279 private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2280 StorageOperationStatus addArtToInst;
2282 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
2283 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2284 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2285 throw new ByResponseFormatComponentException(componentsUtils
2286 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2290 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2291 StorageOperationStatus addArtToInst = toscaOperationFacade
2292 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2293 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2294 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2295 throw new ByResponseFormatComponentException(componentsUtils
2296 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2300 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2301 if (MapUtils.isNotEmpty(instInputs)) {
2302 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2303 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2304 if (addInputToInst.isRight()) {
2305 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2306 addInputToInst.right().value());
2307 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
2308 componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2313 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2314 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2315 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2316 if (addPropToInst.isRight()) {
2317 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2318 addPropToInst.right().value());
2319 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
2320 componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2324 private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2325 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2326 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2327 if (getResourceRes.isRight()) {
2328 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2329 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2330 throw new ByResponseFormatComponentException(responseFormat);
2332 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2333 uploadResInstancesMap);
2334 if (getResourceRes.isRight()) {
2335 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2336 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2337 throw new ByResponseFormatComponentException(responseFormat);
2342 private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2343 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2344 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2345 ComponentInstance currentCompInstance = null;
2346 for (ComponentInstance compInstance : componentInstancesList) {
2348 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2349 currentCompInstance = compInstance;
2354 if (currentCompInstance == null) {
2355 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2356 resource.getUniqueId());
2357 BeEcompErrorManager.getInstance().logInternalDataError(
2358 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2359 resource.getUniqueId(), ErrorSeverity.ERROR);
2360 ResponseFormat responseFormat = componentsUtils
2361 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2362 throw new ByResponseFormatComponentException(responseFormat);
2365 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2366 if (addRelationToRiRes.getStatus() != 200) {
2367 throw new ByResponseFormatComponentException(addRelationToRiRes);
2372 private void processComponentInstance(String yamlName, Resource resource, List<ComponentInstance> componentInstancesList, Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<ComponentInstanceProperty>> instProperties, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String, List<PropertyDefinition>> instAttributes, Map<String, Resource> originCompMap, Map<String, List<ComponentInstanceInput>> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) {
2373 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2374 .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
2376 if (!currentCompInstanceOpt.isPresent()) {
2377 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2378 resource.getUniqueId());
2379 BeEcompErrorManager.getInstance().logInternalDataError(
2380 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2381 resource.getUniqueId(), ErrorSeverity.ERROR);
2382 ResponseFormat responseFormat = componentsUtils
2383 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2384 throw new ByResponseFormatComponentException(responseFormat);
2386 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2387 String resourceInstanceId = currentCompInstance.getUniqueId();
2388 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
2389 if (isNotEmpty(originResource.getRequirements())) {
2390 instRequirements.put(currentCompInstance, originResource.getRequirements());
2392 if (isNotEmpty(originResource.getCapabilities())) {
2393 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2394 currentCompInstance, originResource);
2396 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
2397 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2399 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2400 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2402 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2403 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2405 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2406 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2407 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
2408 if (addPropertiesValueToRiRes.getStatus() != 200) {
2409 throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
2412 addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2413 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
2417 private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2418 Resource originResource;
2419 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2420 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2421 .getToscaFullElement(currentCompInstance.getComponentUid());
2422 if (getOriginResourceRes.isRight()) {
2423 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2424 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2425 getOriginResourceRes);
2426 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2427 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2428 throw new ByResponseFormatComponentException(responseFormat);
2430 originResource = getOriginResourceRes.left().value();
2431 originCompMap.put(originResource.getUniqueId(), originResource);
2433 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2435 return originResource;
2438 private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2439 Map<String, List<CapabilityDefinition>> originCapabilities;
2440 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2441 originCapabilities = new HashMap<>();
2442 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2443 originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v));
2444 uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
2445 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2447 originCapabilities = originResource.getCapabilities();
2449 instCapabilties.put(currentCompInstance, originCapabilities);
2452 private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2453 originCapabilities.values().stream()
2454 .flatMap(Collection::stream)
2455 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2456 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2459 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2460 for (UploadCapInfo capability : capabilities) {
2461 if (isNotEmpty(capability.getProperties())) {
2462 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2463 .collect(toMap(UploadInfo::getName, p -> p)));
2468 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2469 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2471 originCapabilities.put(type, list);
2474 private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2475 Map<String, DataTypeDefinition> allDataTypes) {
2476 properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2479 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2480 Map<String, DataTypeDefinition> allDataTypes) {
2481 String value = null;
2482 List<GetInputValueDataDefinition> getInputs = null;
2483 boolean isValidate = true;
2484 if (null != propertyInfo && propertyInfo.getValue() != null) {
2485 getInputs = propertyInfo.getGet_input();
2486 isValidate = getInputs == null || getInputs.isEmpty();
2488 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2490 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2491 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2494 property.setValue(value);
2495 return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2498 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2499 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2500 Either<Resource, StorageOperationStatus> updateRes = null;
2501 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2502 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2503 StorageOperationStatus status = toscaOperationFacade
2504 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2505 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2507 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2508 resource.getUniqueId(), status);
2509 updateRes = Either.right(status);
2511 if (updateRes == null) {
2512 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2513 updatedInstCapabilities, updatedInstRequirements);
2514 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2515 resource.getUniqueId());
2516 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2518 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2519 resource.getUniqueId(), status);
2520 updateRes = Either.right(status);
2523 if (updateRes == null) {
2524 updateRes = Either.left(resource);
2529 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2530 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2531 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2532 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2534 componentInstances.stream().forEach(i -> {
2535 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2536 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2537 fillUpdatedInstRequirements(updatedInstRequirements, i,
2538 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2542 private void fillUpdatedInstRequirements(
2543 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2544 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2545 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2546 Set<String> updatedReqNames = new HashSet<>();
2547 if (isNotEmpty(requirementsNamesToUpdate)) {
2548 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2549 updatedRequirements.put(requirements.getKey(),
2550 requirements.getValue().stream()
2551 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2552 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2554 r.setParentName(r.getName());
2555 r.setName(requirementsNamesToUpdate.get(r.getName()));
2556 updatedReqNames.add(r.getName());
2558 }).collect(toList()));
2561 if (isNotEmpty(updatedRequirements)) {
2562 updatedInstRequirements.put(instance, updatedRequirements);
2566 private void fillUpdatedInstCapabilities(
2567 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2568 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2569 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2570 Set<String> updatedCapNames = new HashSet<>();
2571 if (isNotEmpty(capabilitiesNamesToUpdate)) {
2572 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2573 updatedCapabilities.put(requirements.getKey(),
2574 requirements.getValue().stream()
2575 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2576 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2578 c.setParentName(c.getName());
2579 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2580 updatedCapNames.add(c.getName());
2582 }).collect(toList()));
2585 if (isNotEmpty(updatedCapabilities)) {
2586 updatedInstCapabilties.put(instance, updatedCapabilities);
2590 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2591 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2592 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2594 ComponentInstance currentCompInstance = null;
2596 for (ComponentInstance compInstance : componentInstancesList) {
2598 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2599 currentCompInstance = compInstance;
2605 if (currentCompInstance == null) {
2606 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2607 resource.getUniqueId());
2608 BeEcompErrorManager.getInstance().logInternalDataError(
2609 COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2610 resource.getUniqueId(), ErrorSeverity.ERROR);
2611 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2614 String resourceInstanceId = currentCompInstance.getUniqueId();
2616 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2618 if (regMap != null) {
2619 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2621 while (nodesRegValue.hasNext()) {
2622 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2624 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2625 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2626 log.debug("Going to create relation {}", uploadRegInfo.getName());
2627 String regName = uploadRegInfo.getName();
2628 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2629 regCapRelDef.setFromNode(resourceInstanceId);
2630 log.debug("try to find available requirement {} ", regName);
2631 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2632 yamlName, nodesInfoValue, currentCompInstance,
2633 uploadRegInfo.getCapabilityName());
2634 if (eitherReqStatus.isRight()) {
2635 log.debug("failed to find available requirement {} status is {}", regName,
2636 eitherReqStatus.right().value());
2637 return eitherReqStatus.right().value();
2640 RequirementDefinition validReq = eitherReqStatus.left().value();
2641 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2642 .getRelationships();
2643 if (reqAndRelationshipPairList == null) {
2644 reqAndRelationshipPairList = new ArrayList<>();
2646 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2647 reqAndRelationshipPair.setRequirement(regName);
2648 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2649 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2650 RelationshipImpl relationship = new RelationshipImpl();
2651 relationship.setType(validReq.getCapability());
2652 reqAndRelationshipPair.setRelationships(relationship);
2654 ComponentInstance currentCapCompInstance = null;
2655 for (ComponentInstance compInstance : componentInstancesList) {
2656 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2657 currentCapCompInstance = compInstance;
2662 if (currentCapCompInstance == null) {
2663 log.debug("The component instance with name {} not found on resource {} ",
2664 uploadRegInfo.getNode(), resource.getUniqueId());
2665 BeEcompErrorManager.getInstance().logInternalDataError(
2666 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2667 resource.getUniqueId(), ErrorSeverity.ERROR);
2668 return componentsUtils
2669 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2671 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2672 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2673 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2674 currentCapCompInstance, uploadRegInfo);
2675 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2676 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2677 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2678 if (aviableCapForRel == null) {
2679 log.debug("aviable capability was not found. req name is {} component instance is {}",
2680 validReq.getName(), currentCapCompInstance.getUniqueId());
2681 BeEcompErrorManager.getInstance().logInternalDataError(
2682 "aviable capability was not found. req name is " + validReq.getName()
2683 + " component instance is " + currentCapCompInstance.getUniqueId(),
2684 resource.getUniqueId(), ErrorSeverity.ERROR);
2685 return componentsUtils
2686 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2688 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2689 capReqRel.setRelation(reqAndRelationshipPair);
2690 reqAndRelationshipPairList.add(capReqRel);
2691 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2692 relations.add(regCapRelDef);
2695 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
2696 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2698 return componentsUtils.getResponseFormat(ActionStatus.OK);
2701 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2702 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2703 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
2704 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2705 if (MapUtils.isNotEmpty(propMap)) {
2706 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2707 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2709 if (CollectionUtils.isEmpty( originResource.getInputs())) {
2710 log.debug("failed to find properties ");
2711 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2713 originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
2714 for (List<UploadPropInfo> propertyList : propMap.values()) {
2715 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
2717 currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
2718 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2722 private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
2723 UploadPropInfo propertyInfo = propertyList.get(0);
2724 String propName = propertyInfo.getName();
2725 if (!currPropertiesMap.containsKey(propName)) {
2726 log.debug("failed to find property {} ", propName);
2727 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2730 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
2731 ComponentInstanceInput property = null;
2733 String value = null;
2734 List<GetInputValueDataDefinition> getInputs = null;
2735 boolean isValidate = true;
2736 if (propertyInfo.getValue() != null) {
2737 getInputs = propertyInfo.getGet_input();
2738 isValidate = getInputs == null || getInputs.isEmpty();
2740 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2741 curPropertyDef.getType());
2743 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2744 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2747 String innerType = null;
2748 property = new ComponentInstanceInput(curPropertyDef, value, null);
2750 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2752 property.setValue(validPropertyVAlue);
2754 if (isNotEmpty(getInputs)) {
2755 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2756 for (GetInputValueDataDefinition getInput : getInputs) {
2757 List<InputDefinition> inputs = resource.getInputs();
2758 if (CollectionUtils.isEmpty(inputs)) {
2759 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
2760 property, currentCompInstance.getUniqueId());
2761 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2764 Optional<InputDefinition> optional = inputs.stream()
2765 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
2766 if (!optional.isPresent()) {
2767 log.debug("Failed to find input {} ", getInput.getInputName());
2768 // @@TODO error message
2769 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2771 InputDefinition input = optional.get();
2772 getInput.setInputId(input.getUniqueId());
2773 getInputValues.add(getInput);
2775 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2776 processGetInput(getInputValues, inputs, getInputIndex);
2778 property.setGetInputValues(getInputValues);
2780 instPropList.add(property);
2781 // delete overriden property
2782 currPropertiesMap.remove(property.getName());
2785 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
2786 Optional<InputDefinition> optional;
2787 if (getInputIndex != null) {
2788 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
2790 if (!optional.isPresent()) {
2791 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2792 // @@TODO error message
2793 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2795 InputDefinition inputIndex = optional.get();
2796 getInputIndex.setInputId(inputIndex.getUniqueId());
2797 getInputValues.add(getInputIndex);
2801 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
2802 String propName = prop.getName();
2803 if (!currPropertiesMap.containsKey(propName)) {
2804 currPropertiesMap.put(propName, prop);
2808 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2809 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2810 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
2812 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2813 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2815 List<PropertyDefinition> listFromMap = originResource.getProperties();
2816 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
2817 log.debug("failed to find properties ");
2818 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2820 if (listFromMap == null || listFromMap.isEmpty()) {
2821 return componentsUtils.getResponseFormat(ActionStatus.OK);
2823 for (PropertyDefinition prop : listFromMap) {
2824 String propName = prop.getName();
2825 if (!currPropertiesMap.containsKey(propName)) {
2826 currPropertiesMap.put(propName, prop);
2829 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2830 if (propMap != null && propMap.size() > 0) {
2831 for (List<UploadPropInfo> propertyList : propMap.values()) {
2833 UploadPropInfo propertyInfo = propertyList.get(0);
2834 String propName = propertyInfo.getName();
2835 if (!currPropertiesMap.containsKey(propName)) {
2836 log.debug("failed to find property {} ", propName);
2837 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2840 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2841 ComponentInstanceProperty property = null;
2843 String value = null;
2844 List<GetInputValueDataDefinition> getInputs = null;
2845 boolean isValidate = true;
2846 if (propertyInfo.getValue() != null) {
2847 getInputs = propertyInfo.getGet_input();
2848 isValidate = getInputs == null || getInputs.isEmpty();
2850 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2851 curPropertyDef.getType());
2853 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2854 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2857 String innerType = null;
2858 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2860 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2861 property.setValue(validatePropValue);
2863 if (getInputs != null && !getInputs.isEmpty()) {
2864 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2865 for (GetInputValueDataDefinition getInput : getInputs) {
2866 List<InputDefinition> inputs = resource.getInputs();
2867 if (inputs == null || inputs.isEmpty()) {
2868 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2869 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2871 .map(GetInputValueDataDefinition::getInputName)
2872 .collect(toList()).toString());
2874 InputDefinition input = findInputByName(inputs, getInput);
2875 getInput.setInputId(input.getUniqueId());
2876 getInputValues.add(getInput);
2878 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2879 if (getInputIndex != null) {
2880 input = findInputByName(inputs, getInputIndex);
2881 getInputIndex.setInputId(input.getUniqueId());
2882 getInputValues.add(getInputIndex);
2887 property.setGetInputValues(getInputValues);
2889 instPropList.add(property);
2890 // delete overriden property
2891 currPropertiesMap.remove(property.getName());
2894 // add rest of properties
2895 if (!currPropertiesMap.isEmpty()) {
2896 for (PropertyDefinition value : currPropertiesMap.values()) {
2897 instPropList.add(new ComponentInstanceProperty(value));
2900 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2901 return componentsUtils.getResponseFormat(ActionStatus.OK);
2904 // US740820 Relate RIs according to capability name
2905 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
2906 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2907 if (null == uploadReqInfo.getCapabilityName()
2908 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
2912 return findAvailableCapability(validReq, currentCapCompInstance);
2914 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
2917 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
2918 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2919 CapabilityDefinition cap = null;
2920 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
2921 if (!capMap.containsKey(validReq.getCapability())) {
2924 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
2925 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
2926 if (!capByName.isPresent()) {
2929 cap = capByName.get();
2931 if (isBoundedByOccurrences(cap)) {
2932 String leftOccurrences = cap.getLeftOccurrences();
2933 int left = Integer.parseInt(leftOccurrences);
2936 cap.setLeftOccurrences(String.valueOf(left));
2944 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
2945 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
2946 if (capMap.containsKey(validReq.getCapability())) {
2947 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
2949 for (CapabilityDefinition cap : capList) {
2950 if (isBoundedByOccurrences(cap)) {
2951 String leftOccurrences = cap.getLeftOccurrences() != null ?
2952 cap.getLeftOccurrences() : cap.getMaxOccurrences();
2953 int left = Integer.parseInt(leftOccurrences);
2956 cap.setLeftOccurrences(String.valueOf(left));
2967 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
2968 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
2971 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
2972 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2974 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
2975 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
2976 RequirementDefinition validRegDef = null;
2978 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
2979 for (RequirementDefinition reqDef : entry.getValue()) {
2980 if (reqDef.getName().equals(regName)) {
2981 if (reqDef.getMaxOccurrences() != null
2982 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2983 String leftOccurrences = reqDef.getLeftOccurrences();
2984 if (leftOccurrences == null) {
2985 leftOccurrences = reqDef.getMaxOccurrences();
2987 int left = Integer.parseInt(leftOccurrences);
2990 reqDef.setLeftOccurrences(String.valueOf(left));
2991 validRegDef = reqDef;
2997 validRegDef = reqDef;
3003 if (validRegDef != null) {
3008 for (RequirementDefinition reqDef : list) {
3009 if (reqDef.getName().equals(regName)) {
3010 if (reqDef.getMaxOccurrences() != null
3011 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3012 String leftOccurrences = reqDef.getLeftOccurrences();
3013 if (leftOccurrences == null) {
3014 leftOccurrences = reqDef.getMaxOccurrences();
3016 int left = Integer.parseInt(leftOccurrences);
3019 reqDef.setLeftOccurrences(String.valueOf(left));
3020 validRegDef = reqDef;
3026 validRegDef = reqDef;
3032 if (validRegDef == null) {
3033 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3034 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3035 return Either.right(responseFormat);
3037 return Either.left(validRegDef);
3040 private Resource createResourceInstances(String yamlName, Resource resource,
3041 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3042 Map<String, Resource> nodeNamespaceMap) {
3044 Either<Resource, ResponseFormat> eitherResource = null;
3045 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3046 if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3047 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3048 throw new ByResponseFormatComponentException(responseFormat);
3050 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
3051 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
3052 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
3054 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3055 uploadResInstancesMap
3057 .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
3059 if (isNotEmpty(resourcesInstancesMap)) {
3060 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
3061 resourcesInstancesMap, false);
3062 if (status != null && status != StorageOperationStatus.OK) {
3063 log.debug("Failed to add component instances to container component {}", resource.getName());
3064 ResponseFormat responseFormat = componentsUtils
3065 .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
3066 eitherResource = Either.right(responseFormat);
3067 throw new ByResponseFormatComponentException(eitherResource.right().value());
3070 log.debug("*************Going to get resource {}", resource.getUniqueId());
3071 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
3072 .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
3073 log.debug("*************finished to get resource {}", resource.getUniqueId());
3074 if (eitherGetResource.isRight()) {
3075 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3076 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3077 throw new ByResponseFormatComponentException(responseFormat);
3079 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
3080 resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
3081 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3082 BeEcompErrorManager.getInstance().logBeDaoSystemError(
3083 "Error when create resource instance from csar. ComponentInstances list empty");
3084 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3086 return eitherGetResource.left().value();
3089 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3090 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
3091 Either<Resource, ResponseFormat> eitherResource;
3092 log.debug("*************Going to create resource instances {}", yamlName);
3093 // updating type if the type is node type name - we need to take the
3095 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3096 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3097 uploadComponentInstanceInfo
3098 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3100 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3101 existingnodeTypeMap);
3103 ComponentInstance componentInstance = new ComponentInstance();
3104 componentInstance.setComponentUid(refResource.getUniqueId());
3106 Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
3107 if(directives != null && !directives.isEmpty()) {
3108 componentInstance.setDirectives(new ArrayList<>(directives));
3110 UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
3111 if (uploadNodeFilterInfo != null){
3112 componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
3113 componentInstance.getUniqueId()));
3116 ComponentTypeEnum containerComponentType = resource.getComponentType();
3117 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3118 if (containerNodeType.equals(NodeTypeEnum.Resource)
3119 && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3120 && isNotEmpty(refResource.getCapabilities())) {
3121 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3122 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3123 refResource.getUniqueId(), refResource.getCapabilities(),
3124 uploadComponentInstanceInfo.getCapabilities());
3125 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3127 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3129 "createResourceInstances - not found lates version for resource instance with name {} and type ",
3130 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3131 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3132 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3133 throw new ByResponseFormatComponentException(responseFormat);
3135 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3136 componentInstance.setName(uploadComponentInstanceInfo.getName());
3137 componentInstance.setIcon(origResource.getIcon());
3138 resourcesInstancesMap.put(componentInstance, origResource);
3141 private ComponentParametersView getComponentWithInstancesFilter() {
3142 ComponentParametersView parametersView = new ComponentParametersView();
3143 parametersView.disableAll();
3144 parametersView.setIgnoreComponentInstances(false);
3145 parametersView.setIgnoreInputs(false);
3146 // inputs are read when creating
3147 // property values on instances
3148 parametersView.setIgnoreUsers(false);
3149 return parametersView;
3152 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3153 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3154 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3155 if (originCapabilities.containsKey(currEntry.getKey())) {
3156 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3159 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3160 capabilities.getValue().stream().forEach(cap -> {
3161 if (uploadedCapabilities.containsKey(cap.getName())) {
3162 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3163 c.setName(cap.getName());
3164 c.setType(cap.getType());
3172 private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
3173 Map<String, Resource> nodeNamespaceMap) {
3175 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3176 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3177 Resource refResource;
3178 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3179 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3181 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3182 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3183 if (findResourceEither.isRight()) {
3185 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3186 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3187 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3188 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3189 throw new ByResponseFormatComponentException(responseFormat);
3191 refResource = findResourceEither.left().value();
3192 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3194 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3195 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3197 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3198 refResource.getName(), componentState);
3199 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3200 refResource.getComponentType().getValue(), refResource.getName(), componentState);
3201 throw new ByResponseFormatComponentException(responseFormat);
3204 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3205 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3206 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3207 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3208 throw new ByResponseFormatComponentException(responseFormat);
3214 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
3215 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3216 boolean forceCertificationAllowed) {
3218 Either<Resource, ResponseFormat> result = null;
3220 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3221 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3222 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3223 if (result.isRight()) {
3226 resource = result.left().value();
3228 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3229 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
3230 resource, user, false, inTransaction, needLock);
3231 result = eitherPopulated.isLeft() ? Either.left(resource)
3232 : Either.right(eitherPopulated.right().value());
3235 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3236 } catch (Exception e) {
3237 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3238 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3240 if (result == null || result.isRight()) {
3241 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3242 if (!inTransaction) {
3243 titanDao.rollback();
3245 } else if (!inTransaction) {
3251 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
3252 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3253 return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
3254 lifecycleChangeInfo, inTransaction, needLock);
3257 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
3258 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3259 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3263 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
3264 Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
3265 CsarInfo csarInfo, String nodeName, boolean isNested) {
3267 ImmutablePair<Resource, ActionStatus> result = null;
3268 // check if resource already exists (search by tosca name = type)
3269 boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3270 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3271 .getLatestByToscaResourceName(resource.getToscaResourceName());
3273 if (latestByToscaName.isLeft()) {
3274 Resource foundResource = latestByToscaName.left().value();
3275 // we don't allow updating names of top level types
3276 if (!isNestedResource &&
3277 !StringUtils.equals(resource.getName(), foundResource.getName())) {
3278 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3279 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3280 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3281 foundResource.getName(), resource.getToscaResourceName());
3282 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3283 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3284 throwComponentException(responseFormat);
3286 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3287 } else if (isNotFound(latestByToscaName)) {
3288 if (isNestedResource) {
3289 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
3291 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3294 StorageOperationStatus status = latestByToscaName.right().value();
3295 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3296 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3297 componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
3298 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3299 throwComponentException(responseFormat);
3304 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3305 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3308 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
3309 Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
3310 resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
3311 if (latestByToscaName.isLeft()) {
3312 Resource nestedResource = (Resource) latestByToscaName.left().value();
3313 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3314 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
3315 ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3316 if (eitherValidation.isRight()) {
3317 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3319 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3321 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3325 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3326 return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
3329 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
3330 User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3331 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3332 validateResourceBeforeCreate(resource, user,
3333 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3334 Resource createdResource = createResourceByDao(resource, user,
3335 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
3336 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
3337 ActionStatus.CREATED);
3338 ASDCKpiApi.countImportResourcesKPI();
3339 return resourcePair;
3342 public boolean isResourceExist(String resourceName) {
3343 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3344 return latestByName.isLeft();
3347 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3348 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3350 String lockedResourceId = oldResource.getUniqueId();
3351 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3352 oldResource.getVersion(), oldResource.getLifecycleState());
3353 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3355 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3356 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3357 mergeOldResourceMetadataWithNew(oldResource, newResource);
3359 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3360 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3361 // contact info normalization
3362 newResource.setContactId(newResource.getContactId().toLowerCase());
3363 // non-updatable fields
3364 newResource.setCreatorUserId(user.getUserId());
3365 newResource.setCreatorFullName(user.getFullName());
3366 newResource.setLastUpdaterUserId(user.getUserId());
3367 newResource.setLastUpdaterFullName(user.getFullName());
3368 newResource.setUniqueId(oldResource.getUniqueId());
3369 newResource.setVersion(oldResource.getVersion());
3370 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3371 newResource.setLifecycleState(oldResource.getLifecycleState());
3372 newResource.setUUID(oldResource.getUUID());
3373 newResource.setNormalizedName(oldResource.getNormalizedName());
3374 newResource.setSystemName(oldResource.getSystemName());
3375 if (oldResource.getCsarUUID() != null) {
3376 newResource.setCsarUUID(oldResource.getCsarUUID());
3378 if (oldResource.getImportedToscaChecksum() != null) {
3379 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3381 newResource.setAbstract(oldResource.isAbstract());
3383 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
3384 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3386 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3387 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3389 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3390 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3393 // created without tosca artifacts - add the placeholders
3394 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3395 setToscaArtifactsPlaceHolders(newResource, user);
3398 if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3399 newResource.setInterfaces(oldResource.getInterfaces());
3402 if (CollectionUtils.isEmpty(newResource.getProperties())) {
3403 newResource.setProperties(oldResource.getProperties());
3406 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3407 .overrideComponent(newResource, oldResource);
3409 if (overrideResource.isRight()) {
3410 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3411 componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3412 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3414 throwComponentException(responseFormat);
3417 log.debug("Resource updated successfully!!!");
3418 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3419 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3420 ResourceVersionInfo.newBuilder()
3421 .state(oldResource.getLifecycleState()
3423 .version(oldResource.getVersion())
3426 resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3428 return resourcePair;
3430 if (resourcePair == null) {
3431 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3432 titanDao.rollback();
3433 } else if (!inTransaction) {
3437 log.debug("unlock resource {}", lockedResourceId);
3438 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3445 * Merge old resource with new. Keep old category and vendor name without
3448 * @param oldResource
3449 * @param newResource
3451 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3453 // keep old category and vendor name without change
3454 // merge the rest of the resource metadata
3455 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3456 newResource.setTags(oldResource.getTags());
3459 if (newResource.getDescription() == null) {
3460 newResource.setDescription(oldResource.getDescription());
3463 if (newResource.getVendorRelease() == null) {
3464 newResource.setVendorRelease(oldResource.getVendorRelease());
3467 if (newResource.getResourceVendorModelNumber() == null) {
3468 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3471 if (newResource.getContactId() == null) {
3472 newResource.setContactId(oldResource.getContactId());
3475 newResource.setCategories(oldResource.getCategories());
3476 if (newResource.getVendorName() == null) {
3477 newResource.setVendorName(oldResource.getVendorName());
3481 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3482 boolean inTransaction, boolean needLock) {
3484 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3486 return lifecycleBusinessLogic.changeState(
3487 oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3488 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3490 .on(response -> failOnChangeState(response, user, oldResource, newResource));
3495 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3496 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3497 response.getFormattedMessage());
3498 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3499 ResourceVersionInfo.newBuilder()
3500 .state(oldResource.getLifecycleState().name())
3501 .version(oldResource.getVersion())
3503 throw new ByResponseFormatComponentException(response);
3506 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3508 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3509 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3510 validateLifecycleTypesCreate(user, resource, actionEnum);
3511 validateResourceType(user, resource, actionEnum);
3512 resource.setCreatorUserId(user.getUserId());
3513 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3514 resource.setContactId(resource.getContactId().toLowerCase());
3515 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3516 String resourceSystemName;
3517 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3518 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3520 resourceSystemName = resource.getSystemName();
3522 resource.setToscaResourceName(CommonBeUtils
3523 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3526 // Generate invariant UUID - must be here and not in operation since it
3527 // should stay constant during clone
3529 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3530 resource.setInvariantUUID(invariantUUID);
3535 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3536 AuditingActionEnum actionEnum) {
3537 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3538 if (resource.getResourceType() == null) {
3539 log.debug("Invalid resource type for resource");
3540 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3541 eitherResult = Either.right(errorResponse);
3542 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3544 return eitherResult;
3547 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3548 AuditingActionEnum actionEnum) {
3549 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3550 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3551 log.debug("validate interface lifecycle Types Exist");
3552 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3553 while (intItr.hasNext() && eitherResult.isLeft()) {
3554 InterfaceDefinition interfaceDefinition = intItr.next();
3555 String intType = interfaceDefinition.getUniqueId();
3556 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3557 .getInterface(intType);
3558 if (eitherCapTypeFound.isRight()) {
3559 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3560 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3561 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3562 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3563 intType, resource.getName());
3564 BeEcompErrorManager.getInstance()
3565 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3566 log.debug("request to data model failed with error: {}",
3567 eitherCapTypeFound.right().value().name());
3570 ResponseFormat errorResponse = componentsUtils
3571 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3572 eitherResult = Either.right(errorResponse);
3573 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3578 return eitherResult;
3581 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3582 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3583 boolean inTransaction) {
3585 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3586 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3587 log.debug("validate capability Types Exist - capabilities section");
3589 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3591 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3592 eitherResult, typeEntry, inTransaction);
3593 if (eitherResult.isRight()) {
3594 return Either.right(eitherResult.right().value());
3599 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3600 log.debug("validate capability Types Exist - requirements section");
3601 for (String type : resource.getRequirements().keySet()) {
3602 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3603 resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3604 if (eitherResult.isRight()) {
3605 return Either.right(eitherResult.right().value());
3610 return eitherResult;
3613 // @param typeObject- the object to which the validation is done
3614 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3615 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3616 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3617 boolean inTransaction) {
3618 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3619 .getCapabilityType(type, inTransaction);
3620 if (eitherCapTypeFound.isRight()) {
3621 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3622 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3623 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3624 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3625 resource.getName());
3626 BeEcompErrorManager.getInstance()
3627 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3629 log.debug("Trying to get capability type {} failed with error: {}", type,
3630 eitherCapTypeFound.right().value().name());
3631 ResponseFormat errorResponse = null;
3633 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3635 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3638 eitherResult = Either.right(errorResponse);
3639 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3641 return eitherResult;
3644 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3645 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3646 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3647 boolean inTransaction) {
3648 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3649 .getCapabilityType(typeEntry.getKey(), inTransaction);
3650 if (eitherCapTypeFound.isRight()) {
3651 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3652 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3653 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3654 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3655 typeEntry.getKey(), resource.getName());
3656 BeEcompErrorManager.getInstance()
3657 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3659 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3660 eitherCapTypeFound.right().value().name());
3661 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3662 typeEntry.getKey());
3663 eitherResult = Either.right(errorResponse);
3664 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3666 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3667 if (capabilityTypeDefinition.getProperties() != null) {
3668 for (CapabilityDefinition capDef : typeEntry.getValue()) {
3669 List<ComponentInstanceProperty> properties = capDef.getProperties();
3670 if (properties == null || properties.isEmpty()) {
3671 properties = new ArrayList<>();
3672 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3673 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3674 properties.add(newProp);
3677 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3678 PropertyDefinition porpFromDef = prop.getValue();
3679 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3680 for (ComponentInstanceProperty cip : properties) {
3681 if (!cip.getName().equals(porpFromDef.getName())) {
3682 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3683 propsToAdd.add(newProp);
3686 if (!propsToAdd.isEmpty()) {
3687 properties.addAll(propsToAdd);
3691 capDef.setProperties(properties);
3694 return eitherResult;
3697 public Resource createResourceByDao(Resource resource, User user,
3698 AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3701 // lock new resource name in order to avoid creation resource with same
3703 Resource createdResource = null;
3704 if (!inTransaction) {
3705 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3707 if (lockResult.isRight()) {
3708 ResponseFormat responseFormat = lockResult.right().value();
3709 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3710 throw new ByResponseFormatComponentException(responseFormat);
3713 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3716 if (resource.deriveFromGeneric()) {
3717 handleResourceGenericType(resource);
3719 createdResource = createResourceTransaction(resource, user, isNormative
3721 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3722 createdResource, actionEnum);
3723 ASDCKpiApi.countCreatedResourcesKPI();
3724 } catch(ByActionStatusComponentException e) {
3725 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3726 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3728 } catch(ByResponseFormatComponentException e) {
3729 ResponseFormat responseFormat = e.getResponseFormat();
3730 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3732 } catch (StorageException e){
3733 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3734 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3738 if (!inTransaction) {
3739 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3740 NodeTypeEnum.Resource);
3743 return createdResource;
3746 private Resource createResourceTransaction(Resource resource, User user,
3747 boolean isNormative) {
3748 // validate resource name uniqueness
3749 log.debug("validate resource name");
3750 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3751 resource.getName(), resource.getResourceType(), resource.getComponentType());
3752 if (eitherValidation.isRight()) {
3753 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3754 eitherValidation.right().value());
3755 ResponseFormat errorResponse = componentsUtils
3756 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3757 throw new ByResponseFormatComponentException(errorResponse);
3759 if (eitherValidation.left().value()) {
3760 log.debug("resource with name: {}, already exists", resource.getName());
3761 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3762 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3763 throw new ByResponseFormatComponentException(errorResponse);
3766 log.debug("send resource {} to dao for create", resource.getName());
3768 createArtifactsPlaceHolderData(resource, user);
3771 log.debug("enrich resource with creator, version and state");
3772 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3773 resource.setVersion(INITIAL_VERSION);
3774 resource.setHighestVersion(true);
3775 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3776 resource.setAbstract(false);
3779 return toscaOperationFacade.createToscaComponent(resource)
3781 .on(r->throwComponentExceptionByResource(r, resource));
3784 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3785 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3786 componentsUtils.convertFromStorageResponse(status), resource);
3787 throw new ByResponseFormatComponentException(responseFormat);
3790 private void createArtifactsPlaceHolderData(Resource resource, User user) {
3791 // create mandatory artifacts
3793 // TODO it must be removed after that artifact uniqueId creation will be
3794 // moved to ArtifactOperation
3796 setInformationalArtifactsPlaceHolder(resource, user);
3797 setDeploymentArtifactsPlaceHolder(resource, user);
3798 setToscaArtifactsPlaceHolders(resource, user);
3801 @SuppressWarnings("unchecked")
3803 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3804 Resource resource = (Resource) component;
3805 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3806 if (artifactMap == null) {
3807 artifactMap = new HashMap<>();
3809 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3810 .getConfiguration().getDeploymentResourceArtifacts();
3811 if (deploymentResourceArtifacts != null) {
3812 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3813 deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3815 resource.setDeploymentArtifacts(artifactMap);
3818 private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3819 boolean shouldCreateArtifact = true;
3820 Map<String, Object> artifactDetails = (Map<String, Object>) v;
3821 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3822 if (object != null) {
3823 List<String> artifactTypes = (List<String>) object;
3824 if (!artifactTypes.contains(resource.getResourceType().name())) {
3825 shouldCreateArtifact = false;
3829 log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3832 if (shouldCreateArtifact) {
3833 if (artifactsBusinessLogic != null) {
3834 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3835 resource.getUniqueId(), k, (Map<String, Object>) v,
3836 user, ArtifactGroupTypeEnum.DEPLOYMENT);
3837 if (artifactDefinition != null
3838 && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3839 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3845 @SuppressWarnings("unchecked")
3846 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3847 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3848 if (artifactMap == null) {
3849 artifactMap = new HashMap<>();
3851 String resourceUniqueId = resource.getUniqueId();
3852 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3853 .getExcludeResourceCategory();
3854 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3855 .getExcludeResourceType();
3856 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3857 .getConfiguration().getInformationalResourceArtifacts();
3858 List<CategoryDefinition> categories = resource.getCategories();
3859 boolean isCreateArtifact = true;
3860 if (exludeResourceCategory != null) {
3861 String category = categories.get(0).getName();
3862 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3864 if (isCreateArtifact && exludeResourceType != null) {
3865 String resourceType = resource.getResourceType().name();
3866 isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3868 if (informationalResourceArtifacts != null && isCreateArtifact) {
3869 Set<String> keys = informationalResourceArtifacts.keySet();
3870 for (String informationalResourceArtifactName : keys) {
3871 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3872 .get(informationalResourceArtifactName);
3873 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3874 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3875 ArtifactGroupTypeEnum.INFORMATIONAL);
3876 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3880 resource.setArtifacts(artifactMap);
3890 public ResponseFormat deleteResource(String resourceId, User user) {
3891 ResponseFormat responseFormat;
3892 validateUserExists(user, DELETE_RESOURCE, false);
3894 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3895 if (resourceStatus.isRight()) {
3896 log.debug("failed to get resource {}", resourceId);
3897 return componentsUtils
3898 .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3901 Resource resource = resourceStatus.left().value();
3903 StorageOperationStatus result = StorageOperationStatus.OK;
3904 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3905 if (lockResult.isRight()) {
3906 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3911 result = markComponentToDelete(resource);
3912 if (result.equals(StorageOperationStatus.OK)) {
3913 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3915 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3916 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3918 return responseFormat;
3921 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3922 titanDao.rollback();
3926 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3931 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3932 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3933 validateUserExists(user, DELETE_RESOURCE, false);
3934 Resource resource = null;
3935 StorageOperationStatus result = StorageOperationStatus.OK;
3938 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3939 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3940 if (resourceStatus.isRight()) {
3941 log.debug("failed to get resource {} version {}", resourceName, version);
3942 return componentsUtils.getResponseFormatByResource(
3943 componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3946 resource = resourceStatus.left().value();
3949 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3950 titanDao.rollback();
3951 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3952 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3957 if (resource != null) {
3958 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3960 if (lockResult.isRight()) {
3961 result = StorageOperationStatus.GENERAL_ERROR;
3962 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3965 result = markComponentToDelete(resource);
3966 if (!result.equals(StorageOperationStatus.OK)) {
3967 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3968 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3969 return responseFormat;
3973 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3974 titanDao.rollback();
3978 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3981 return responseFormat;
3984 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3987 validateUserExists(user, CREATE_RESOURCE, false);
3990 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3991 if (storageStatus.isRight()) {
3992 log.debug("failed to get resource by id {}", resourceId);
3993 return Either.right(componentsUtils.getResponseFormatByResource(
3994 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3996 if (!(storageStatus.left().value() instanceof Resource)) {
3997 return Either.right(componentsUtils.getResponseFormatByResource(
3998 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
4000 return Either.left(storageStatus.left().value());
4004 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
4007 validateUserExists(userId, "get Resource By Name And Version", false);
4009 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
4010 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
4011 if (getResource.isRight()) {
4012 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
4013 return Either.right(componentsUtils.getResponseFormatByResource(
4014 componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
4016 return Either.left(getResource.left().value());
4020 * updateResourceMetadata
4022 * @param user - modifier data (userId)
4023 * @param inTransaction TODO
4024 * @param resourceIdToUpdate - the resource identifier
4025 * @param newResource
4026 * @return Either<Resource , responseFormat>
4028 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4029 Resource currentResource, User user, boolean inTransaction) {
4031 validateUserExists(user.getUserId(), "update Resource Metadata", false);
4033 log.debug("Get resource with id {}", resourceIdToUpdate);
4034 boolean needToUnlock = false;
4035 boolean rollbackNeeded = true;
4038 if (currentResource == null) {
4039 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
4040 .getToscaElement(resourceIdToUpdate);
4041 if (storageStatus.isRight()) {
4042 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
4043 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
4046 currentResource = storageStatus.left().value();
4048 // verify that resource is checked-out and the user is the last
4050 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
4051 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
4055 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
4056 NodeTypeEnum.Resource);
4057 if (!lockResult.equals(StorageOperationStatus.OK)) {
4058 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
4059 NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
4060 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
4061 ResponseFormat responseFormat = componentsUtils
4062 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
4063 throw new ByResponseFormatComponentException(responseFormat);
4066 needToUnlock = true;
4068 // critical section starts here
4069 // convert json to object
4071 // Update and updated resource must have a non-empty "derivedFrom"
4073 // This code is not called from import resources, because of root
4074 // VF "derivedFrom" should be null (or ignored)
4075 if (ModelConverter.isAtomicComponent(currentResource)) {
4076 validateDerivedFromNotEmpty(null, newResource, null);
4077 validateDerivedFromNotEmpty(null, currentResource, null);
4079 newResource.setDerivedFrom(null);
4082 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
4083 user, currentResource, false, true);
4084 if (dataModelResponse.isRight()) {
4085 log.debug("failed to update resource metadata!!!");
4086 rollbackNeeded = true;
4087 throw new ByResponseFormatComponentException(dataModelResponse.right().value());
4090 log.debug("Resource metadata updated successfully!!!");
4091 rollbackNeeded = false;
4092 return dataModelResponse.left().value();
4094 } catch (ComponentException|StorageException e){
4095 rollback(inTransaction, newResource, null, null);
4099 if (!inTransaction) {
4103 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4108 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4109 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4110 updateVfModuleGroupsNames(currentResource, newResource);
4111 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4112 // Setting last updater and uniqueId
4113 newResource.setContactId(newResource.getContactId().toLowerCase());
4114 newResource.setLastUpdaterUserId(user.getUserId());
4115 newResource.setUniqueId(resourceIdToUpdate);
4116 // Cannot set highest version through UI
4117 newResource.setHighestVersion(currentResource.isHighestVersion());
4118 newResource.setCreationDate(currentResource.getCreationDate());
4120 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4121 newResource, user.getUserId(), inTransaction);
4123 if (processUpdateOfDerivedFrom.isRight()) {
4124 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4125 return Either.right(processUpdateOfDerivedFrom.right().value());
4128 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4129 if (isNotEmpty(newResource.getGroups())) {
4130 for (GroupDefinition group : newResource.getGroups()) {
4131 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4132 groupBusinessLogic.validateAndUpdateGroupMetadata(
4133 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4134 user, newResource.getComponentType(), group, true, false);
4138 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4139 .updateToscaElement(newResource);
4141 if (dataModelResponse.isRight()) {
4142 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4143 componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4144 return Either.right(responseFormat);
4145 } else if (dataModelResponse.left().value() == null) {
4146 log.debug("No response from updateResource");
4147 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4149 return Either.left(dataModelResponse.left().value());
4153 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4154 if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4155 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4157 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4159 newResource.setGroups(updatedGroups);
4163 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4164 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4165 if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4166 String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4167 String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4168 updatedGroup.setName(newGroupName);
4170 return updatedGroup;
4173 * validateResourceFieldsBeforeCreate
4175 * @param user - modifier data (userId)
4176 * @return Either<Boolean , ErrorResponse>
4178 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4179 AuditingActionEnum actionEnum, boolean inTransaction) {
4180 validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4181 // validate category
4182 log.debug("validate category");
4183 validateCategory(user, resource, actionEnum, inTransaction);
4184 // validate vendor name & release & model number
4185 log.debug("validate vendor name");
4186 validateVendorName(user, resource, actionEnum);
4187 log.debug("validate vendor release");
4188 validateVendorReleaseName(user, resource, actionEnum);
4189 log.debug("validate resource vendor model number");
4190 validateResourceVendorModelNumber(user, resource, actionEnum);
4192 log.debug("validate cost");
4193 validateCost(resource);
4194 // validate licenseType
4195 log.debug("validate licenseType");
4196 validateLicenseType(user, resource, actionEnum);
4197 // validate template (derived from)
4198 log.debug("validate derived from");
4199 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4200 resource.setDerivedFrom(null);
4202 validateDerivedFromExist(user, resource, actionEnum);
4203 // warn about non-updatable fields
4204 checkComponentFieldsForOverrideAttempt(resource);
4205 String currentCreatorFullName = resource.getCreatorFullName();
4206 if (currentCreatorFullName != null) {
4207 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4210 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4211 if (currentLastUpdaterFullName != null) {
4212 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4215 Long currentLastUpdateDate = resource.getLastUpdateDate();
4216 if (currentLastUpdateDate != null) {
4217 log.debug("Resource last update date is automatically set and cannot be updated");
4220 Boolean currentAbstract = resource.isAbstract();
4221 if (currentAbstract != null) {
4222 log.debug("Resource abstract is automatically set and cannot be updated");
4225 return Either.left(true);
4229 * validateResourceFieldsBeforeUpdate
4231 * @param currentResource - Resource object to validate
4234 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4235 boolean inTransaction, boolean isNested) {
4236 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4237 warnNonEditableFields(currentResource, updateInfoResource);
4240 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4241 String currentResourceVersion = currentResource.getVersion();
4242 String updatedResourceVersion = updateInfoResource.getVersion();
4244 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4245 log.debug("Resource version is automatically set and cannot be updated");
4248 String currentCreatorUserId = currentResource.getCreatorUserId();
4249 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4251 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4252 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4255 String currentCreatorFullName = currentResource.getCreatorFullName();
4256 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4258 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4259 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4262 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4263 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4265 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4266 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4269 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4270 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4272 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4273 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4276 Long currentCreationDate = currentResource.getCreationDate();
4277 Long updatedCreationDate = updateInfoResource.getCreationDate();
4279 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4280 log.debug("Resource Creation date is automatically set and cannot be updated");
4283 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4284 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4286 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4287 log.debug("Resource last update date is automatically set and cannot be updated");
4290 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4291 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4293 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4294 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4297 Boolean currentAbstract = currentResource.isAbstract();
4298 Boolean updatedAbstract = updateInfoResource.isAbstract();
4300 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4301 log.debug("Resource abstract is automatically set and cannot be updated");
4304 Boolean currentHighestVersion = currentResource.isHighestVersion();
4305 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4307 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4308 log.debug("Resource highest version is automatically set and cannot be updated");
4311 String currentUuid = currentResource.getUUID();
4312 String updatedUuid = updateInfoResource.getUUID();
4314 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4315 log.debug("Resource UUID is automatically set and cannot be updated");
4318 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4319 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4321 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4322 log.debug("Resource Type cannot be updated");
4325 updateInfoResource.setResourceType(currentResource.getResourceType());
4327 String currentInvariantUuid = currentResource.getInvariantUUID();
4328 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4330 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4331 log.debug("Resource invariant UUID is automatically set and cannot be updated");
4332 updateInfoResource.setInvariantUUID(currentInvariantUuid);
4336 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4337 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4338 log.debug("validate resource name before update");
4339 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4340 log.debug("validate description before update");
4341 validateDescriptionAndCleanup(null, updateInfoResource, null);
4342 log.debug("validate icon before update");
4343 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4344 log.debug("validate tags before update");
4345 validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4346 log.debug("validate vendor name before update");
4347 validateVendorName(null, updateInfoResource, null);
4348 log.debug("validate resource vendor model number before update");
4349 validateResourceVendorModelNumber(currentResource, updateInfoResource);
4350 log.debug("validate vendor release before update");
4351 validateVendorReleaseName(null, updateInfoResource, null);
4352 log.debug("validate contact info before update");
4353 validateContactId(null, updateInfoResource, null);
4354 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4355 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4356 log.debug("validate category before update");
4357 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4361 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4362 String resourceNameUpdated = updateInfoResource.getName();
4363 String resourceNameCurrent = currentResource.getName();
4364 if (resourceNameCurrent.equals(resourceNameUpdated)) {
4367 // In case of CVFC type we should support the case of old VF with CVFC
4368 // instances that were created without the "Cvfc" suffix
4369 return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4370 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4373 private String addCvfcSuffixToResourceName(String resourceName) {
4374 return resourceName + "Cvfc";
4377 private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4378 boolean hasBeenCertified, boolean isNested) {
4379 String resourceNameUpdated = updateInfoResource.getName();
4380 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4381 if (isNested || !hasBeenCertified) {
4382 validateComponentName(null, updateInfoResource, null);
4383 validateResourceNameUniqueness(updateInfoResource);
4384 currentResource.setName(resourceNameUpdated);
4385 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4386 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4389 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4390 resourceNameUpdated);
4391 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4396 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4397 String iconUpdated = updateInfoResource.getIcon();
4398 String iconCurrent = currentResource.getIcon();
4399 if (!iconCurrent.equals(iconUpdated)) {
4400 if (!hasBeenCertified) {
4401 validateIcon(null, updateInfoResource, null);
4403 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4404 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4409 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4410 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4411 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4412 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4413 validateResourceVendorModelNumber(null, updateInfoResource, null);
4417 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4418 boolean hasBeenCertified, boolean inTransaction) {
4419 validateCategory(null, updateInfoResource, null, inTransaction);
4420 if (hasBeenCertified) {
4421 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4422 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4423 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4424 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4425 if (!currentCategory.getName().equals(updateCategory.getName())
4426 || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4427 log.info("Category {} cannot be updated once the resource has been certified once.",
4428 currentResource.getCategories());
4429 ResponseFormat errorResponse = componentsUtils
4430 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4431 return Either.right(errorResponse);
4434 return Either.left(true);
4437 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4438 Resource updateInfoResource, boolean hasBeenCertified) {
4440 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4441 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4442 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4443 || updatedDerivedFrom.isEmpty()) {
4444 log.trace("Update normative types");
4445 return Either.left(true);
4448 String derivedFromCurrent = currentDerivedFrom.get(0);
4449 String derivedFromUpdated = updatedDerivedFrom.get(0);
4451 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4452 if (!hasBeenCertified) {
4453 validateDerivedFromExist(null, updateInfoResource, null);
4455 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4456 currentResource, updateInfoResource, null);
4458 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4459 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4460 return validateDerivedFromExtending;
4464 // For derived from, we must know whether it was actually changed,
4465 // otherwise we must do no action.
4466 // Due to changes it inflicts on data model (remove artifacts,
4467 // properties...), it's not like a flat field which can be
4468 // overwritten if not changed.
4469 // So we must indicate that derived from is not changed
4470 updateInfoResource.setDerivedFrom(null);
4472 return Either.left(true);
4475 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4476 Resource updateInfoResource, boolean hasBeenCertified) {
4478 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4479 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4480 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4481 || updatedDerivedFrom.isEmpty()) {
4482 log.trace("Update normative types");
4483 return Either.left(true);
4486 String derivedFromCurrent = currentDerivedFrom.get(0);
4487 String derivedFromUpdated = updatedDerivedFrom.get(0);
4489 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4490 if (!hasBeenCertified) {
4491 validateDerivedFromExist(null, updateInfoResource, null);
4493 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4494 currentResource, updateInfoResource, null);
4496 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4497 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4498 return validateDerivedFromExtending;
4502 return Either.left(true);
4505 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
4506 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4509 String templateName = resource.getDerivedFrom().get(0);
4510 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4511 .validateToscaResourceNameExists(templateName);
4512 if (dataModelResponse.isRight()) {
4513 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4514 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4515 log.debug("request to data model failed with error: {}", storageStatus);
4516 ResponseFormat responseFormat = componentsUtils
4517 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4518 log.trace("audit before sending response");
4519 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4520 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4521 } else if (!dataModelResponse.left().value()) {
4522 log.info("resource template with name: {}, does not exists", templateName);
4523 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4524 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4525 throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4529 // Tal G for extending inheritance US815447
4530 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4531 Resource updateInfoResource, AuditingActionEnum actionEnum) {
4532 String currentTemplateName = currentResource.getDerivedFrom().get(0);
4533 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4535 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4536 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4537 if (dataModelResponse.isRight()) {
4538 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4539 BeEcompErrorManager.getInstance()
4540 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4541 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4542 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4543 log.trace("audit before sending response");
4544 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4545 return Either.right(responseFormat);
4548 if (!dataModelResponse.left().value()) {
4549 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4550 currentTemplateName);
4551 ResponseFormat responseFormat = componentsUtils
4552 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4553 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4555 return Either.right(responseFormat);
4558 return Either.left(true);
4561 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4562 log.debug("validate resource derivedFrom field");
4563 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4564 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4565 log.info("derived from (template) field is missing for the resource");
4566 ResponseFormat responseFormat = componentsUtils
4567 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4568 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4570 throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4574 private void validateResourceNameUniqueness(Resource resource) {
4576 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4577 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4578 resource.getComponentType());
4579 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4580 log.debug("resource with name: {}, already exists", resource.getName());
4581 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4582 resource.getName());
4583 } else if(resourceOperationResponse.isRight()){
4584 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4585 throw new StorageException(resourceOperationResponse.right().value());
4590 private void validateCategory(User user, Resource resource,
4591 AuditingActionEnum actionEnum, boolean inTransaction) {
4593 List<CategoryDefinition> categories = resource.getCategories();
4594 if (CollectionUtils.isEmpty(categories)) {
4595 log.debug(CATEGORY_IS_EMPTY);
4596 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4597 ComponentTypeEnum.RESOURCE.getValue());
4598 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4599 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4600 ComponentTypeEnum.RESOURCE.getValue());
4602 if (categories.size() > 1) {
4603 log.debug("Must be only one category for resource");
4604 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4606 CategoryDefinition category = categories.get(0);
4607 List<SubCategoryDefinition> subcategories = category.getSubcategories();
4608 if (CollectionUtils.isEmpty(subcategories)) {
4609 log.debug("Missinig subcategory for resource");
4610 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4612 if (subcategories.size() > 1) {
4613 log.debug("Must be only one sub category for resource");
4614 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4617 SubCategoryDefinition subcategory = subcategories.get(0);
4619 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4620 log.debug(CATEGORY_IS_EMPTY);
4621 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4622 ComponentTypeEnum.RESOURCE.getValue());
4623 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4624 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4625 ComponentTypeEnum.RESOURCE.getValue());
4627 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4628 log.debug(CATEGORY_IS_EMPTY);
4629 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4630 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4631 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4632 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4635 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4638 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4639 User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4640 ResponseFormat responseFormat;
4641 if (category != null && subcategory != null) {
4642 log.debug("validating resource category {} against valid categories list", category);
4643 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4644 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4645 if (categories.isRight()) {
4646 log.debug("failed to retrieve resource categories from Titan");
4647 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4648 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4649 throw new ByActionStatusComponentException(categories.right().value());
4651 List<CategoryDefinition> categoryList = categories.left().value();
4652 Optional<CategoryDefinition> foundCategory = categoryList.stream()
4653 .filter(cat -> cat.getName().equals(category.getName()))
4655 if(!foundCategory.isPresent()){
4656 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4657 category, categoryList);
4658 failOnInvalidCategory(user, resource, actionEnum);
4660 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4663 .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4665 if(!foundSubcategory.isPresent()){
4666 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4667 subcategory, foundCategory.get().getSubcategories());
4668 failOnInvalidCategory(user, resource, actionEnum);
4673 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4674 ResponseFormat responseFormat;
4675 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4676 ComponentTypeEnum.RESOURCE.getValue());
4677 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4678 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4679 ComponentTypeEnum.RESOURCE.getValue());
4682 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4683 String vendorRelease = resource.getVendorRelease();
4684 log.debug("validate vendor relese name");
4685 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4686 log.info("vendor relese name is missing.");
4687 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4688 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4689 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4692 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4695 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4696 if (vendorRelease != null) {
4697 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4698 log.info("vendor release exceds limit.");
4699 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4700 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4701 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4702 throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4705 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4706 log.info("vendor release is not valid.");
4707 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4708 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4709 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4714 private void validateVendorName(User user, Resource resource,
4715 AuditingActionEnum actionEnum) {
4716 String vendorName = resource.getVendorName();
4717 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4718 log.info("vendor name is missing.");
4719 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4720 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4721 throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_NAME);
4723 validateVendorName(vendorName, user, resource, actionEnum);
4726 private void validateVendorName(String vendorName, User user, Resource resource,
4727 AuditingActionEnum actionEnum) {
4728 if (vendorName != null) {
4729 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4730 log.info("vendor name exceds limit.");
4731 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4732 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4733 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4734 throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4735 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4738 if (!ValidationUtils.validateVendorName(vendorName)) {
4739 log.info("vendor name is not valid.");
4740 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4741 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4742 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_NAME);
4747 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4748 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4749 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4750 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4751 log.info("resource vendor model number exceeds limit.");
4752 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4753 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4754 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4755 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4756 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4757 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4759 // resource vendor model number is currently validated as vendor
4761 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4762 log.info("resource vendor model number is not valid.");
4763 ResponseFormat errorResponse = componentsUtils
4764 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4765 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4766 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4772 private void validateCost(Resource resource) {
4773 String cost = resource.getCost();
4775 if (!ValidationUtils.validateCost(cost)) {
4776 log.debug("resource cost is invalid.");
4777 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
4782 private void validateLicenseType(User user, Resource resource,
4783 AuditingActionEnum actionEnum) {
4784 log.debug("validate licenseType");
4785 String licenseType = resource.getLicenseType();
4786 if (licenseType != null) {
4787 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4789 if (!licenseTypes.contains(licenseType)) {
4790 log.debug("License type {} isn't configured", licenseType);
4791 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4792 if (actionEnum != null) {
4793 // In update case, no audit is required
4794 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4796 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
4801 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4802 Resource updatedResource, String userId, boolean inTransaction) {
4803 Either<Operation, ResponseFormat> deleteArtifactByInterface;
4804 if (updatedResource.getDerivedFrom() != null) {
4805 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4806 log.debug("1. Removing interface artifacts from graph");
4807 // Remove all interface artifacts of resource
4808 String resourceId = updatedResource.getUniqueId();
4809 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4811 if (interfaces != null) {
4812 Collection<InterfaceDefinition> values = interfaces.values();
4813 for (InterfaceDefinition interfaceDefinition : values) {
4814 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4816 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4817 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4818 if (operations != null) {
4819 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4820 Operation operation = operationEntry.getValue();
4821 ArtifactDefinition implementation = operation.getImplementationArtifact();
4822 if (implementation != null) {
4823 String uniqueId = implementation.getUniqueId();
4824 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4825 uniqueId, operationEntry.getKey(), interfaceType);
4826 // only thing that transacts and locks here
4827 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4830 if (deleteArtifactByInterface.isRight()) {
4831 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4832 if (!inTransaction) {
4833 titanDao.rollback();
4835 return Either.right(deleteArtifactByInterface.right().value());
4838 log.trace("No implementation found for operation {} - nothing to delete",
4839 operationEntry.getKey());
4843 log.trace("No operations found for interface type {}", interfaceType);
4847 log.debug("2. Removing properties");
4848 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4849 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4851 if (findPropertiesOfNode.isRight()
4852 && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4853 log.debug("Failed to remove all properties of resource");
4854 if (!inTransaction) {
4855 titanDao.rollback();
4857 return Either.right(componentsUtils.getResponseFormat(
4858 componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4862 log.debug("Derived from wasn't changed during update");
4865 if (inTransaction) {
4866 return Either.left(true);
4869 return Either.left(true);
4873 /**** Auditing *******************/
4875 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4876 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4877 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4879 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4881 return webApplicationContext.getBean(class1);
4884 public ICapabilityTypeOperation getCapabilityTypeOperation() {
4885 return capabilityTypeOperation;
4888 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4889 this.capabilityTypeOperation = capabilityTypeOperation;
4892 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4893 log.debug("validate resource properties default values");
4894 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4895 List<PropertyDefinition> properties = resource.getProperties();
4896 if (properties != null) {
4897 eitherResult = iterateOverProperties(properties);
4899 return eitherResult;
4902 public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4903 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4905 String innerType = null;
4906 for (PropertyDefinition property : properties) {
4907 if (!propertyOperation.isPropertyTypeValid(property)) {
4908 log.info("Invalid type for property {}", property);
4909 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4910 ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4911 eitherResult = Either.right(responseFormat);
4915 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4916 applicationDataTypeCache);
4917 if (allDataTypes.isRight()) {
4918 return Either.right(allDataTypes.right().value());
4921 type = property.getType();
4923 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4924 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4925 if(responseFormat != null) {
4929 eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4931 return eitherResult;
4934 private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4935 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4936 log.info("Invalid default value for property {}", property);
4937 ResponseFormat responseFormat;
4938 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4939 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4940 property.getName(), type, innerType, property.getDefaultValue());
4942 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4943 property.getName(), type, property.getDefaultValue());
4945 return Either.right(responseFormat);
4948 return Either.left(true);
4951 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4952 ResponseFormat responseFormat = null;
4953 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4954 .isPropertyInnerTypeValid(property, allDataTypes);
4955 innerType = propertyInnerTypeValid.getLeft();
4956 if (!propertyInnerTypeValid.getRight().booleanValue()) {
4957 log.info("Invalid inner type for property {}", property);
4958 responseFormat = componentsUtils.getResponseFormat(
4959 ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4961 return responseFormat;
4965 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4966 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4970 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4971 return componentInstanceBusinessLogic;
4974 private String getComponentTypeForResponse(Component component) {
4975 String componentTypeForResponse = "SERVICE";
4976 if (component instanceof Resource) {
4977 componentTypeForResponse = ((Resource) component).getResourceType().name();
4979 return componentTypeForResponse;
4982 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4985 validateUserExists(user, "Get resource from csar UUID",
4988 // get resource from csar uuid
4989 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4990 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4991 if (either.isRight()) {
4992 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4994 return Either.right(resp);
4997 return Either.left(either.left().value());
5001 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
5002 String componentId, String userId) {
5006 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
5007 String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
5008 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
5010 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
5011 uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
5012 return validCapabilitiesMap;
5015 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
5016 String capabilityType = capabilities.get(0).getType();
5017 if (defaultCapabilities.containsKey(capabilityType)) {
5018 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
5019 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
5020 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
5021 validCapabilityList.add(defaultCapability);
5022 validCapabilitiesMap.put(key, validCapabilityList);
5024 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
5028 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
5029 if (CollectionUtils.isEmpty(defaultCapability.getProperties())
5030 && isNotEmpty(capabilities.get(0).getProperties())) {
5031 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
5032 defaultCapability.getName(), resourceId);
5034 "Failed to update capability property values. Property list of fetched capability {} is empty. ",
5035 defaultCapability.getName());
5036 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
5037 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
5038 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
5042 private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
5043 CapabilityDefinition defaultCapability;
5044 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
5045 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
5047 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
5048 .getToscaFullElement(resourceId);
5049 if (getFullComponentRes.isRight()) {
5050 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
5051 getFullComponentRes.right().value());
5052 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
5055 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
5057 return defaultCapability;
5060 private void validateUniquenessUpdateUploadedComponentInstanceCapability(
5061 CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
5062 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
5063 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
5064 .collect(toMap(PropertyDefinition::getName, Function.identity()));
5065 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
5066 for (UploadPropInfo property : uploadedProperties) {
5067 String propertyName = property.getName().toLowerCase();
5068 String propertyType = property.getType();
5069 ComponentInstanceProperty validProperty;
5070 if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
5071 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
5074 validProperty = new ComponentInstanceProperty();
5075 validProperty.setName(propertyName);
5076 if (property.getValue() != null) {
5077 validProperty.setValue(property.getValue().toString());
5079 validProperty.setDescription(property.getDescription());
5080 validProperty.setPassword(property.isPassword());
5081 validProperties.add(validProperty);
5083 defaultCapability.setProperties(validProperties);
5086 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
5087 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
5090 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5091 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5092 Resource resource, User user) {
5094 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5095 ArtifactOperationEnum.class);
5096 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5097 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5098 .left(nodeTypeArtifactsToHandle);
5100 // add all found Csar artifacts to list to upload
5101 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5102 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5103 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5104 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5105 ArtifactDefinition foundArtifact;
5107 if (!existingArtifactsToHandle.isEmpty()) {
5108 foundArtifact = existingArtifactsToHandle.stream()
5109 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5111 if (foundArtifact != null) {
5112 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5113 .getArtifactType()) {
5114 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5115 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5116 // if current artifact already exists, but has
5117 // different content, add him to the list to
5119 artifactsToUpdate.add(currNewArtifact);
5121 // remove found artifact from the list of existing
5122 // artifacts to handle, because it was already
5124 existingArtifactsToHandle.remove(foundArtifact);
5125 // and remove found artifact from the list to
5126 // upload, because it should either be updated or be
5128 artifactsToUpload.remove(currNewArtifact);
5130 log.debug("Can't upload two artifact with the same name {}.",
5131 currNewArtifact.getArtifactName());
5132 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5133 ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5134 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5135 foundArtifact.getArtifactType());
5136 AuditingActionEnum auditingAction = artifactsBusinessLogic
5137 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5138 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5139 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5140 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5141 resource.getComponentType(), null);
5142 responseWrapper.setInnerElement(responseFormat);
5148 if (responseWrapper.isEmpty()) {
5149 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5150 if (currArtifact.getIsFromCsar()) {
5151 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5153 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5158 if (responseWrapper.isEmpty()) {
5159 if (!artifactsToUpload.isEmpty()) {
5160 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5162 if (!artifactsToUpdate.isEmpty()) {
5163 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5165 if (!artifactsToDelete.isEmpty()) {
5166 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5169 if (!responseWrapper.isEmpty()) {
5170 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5172 } catch (Exception e) {
5173 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5174 responseWrapper.setInnerElement(responseFormat);
5175 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5176 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5178 return nodeTypeArtifactsToHandleRes;
5181 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5182 String nodeTypeFullName) {
5184 String actualVfName;
5185 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5186 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5187 actualType = ResourceTypeEnum.VFC.name();
5189 actualVfName = vfResourceName;
5190 actualType = nodeResourceType;
5192 String nameWithouNamespacePrefix;
5194 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
5195 if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)){
5196 nameWithouNamespacePrefix = nodeTypeFullName;
5198 nameWithouNamespacePrefix = nodeTypeFullName
5199 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
5201 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5202 String resourceType = findTypes[0];
5203 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
5205 if (actualName.startsWith(Constants.ABSTRACT)) {
5206 toscaResourceName.append(resourceType.toLowerCase()).append('.')
5207 .append(ValidationUtils.convertToSystemName(actualVfName));
5209 toscaResourceName.append(actualType.toLowerCase()).append('.')
5210 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5212 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5213 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5214 previousToscaResourceName
5215 .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
5217 } catch (Exception e) {
5218 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
5219 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5220 throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5224 public ICacheMangerOperation getCacheManagerOperation() {
5225 return cacheManagerOperation;
5228 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
5229 this.cacheManagerOperation = cacheManagerOperation;
5233 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
5234 List<String> dataParamsToReturn) {
5236 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5237 Either<Resource, StorageOperationStatus> resourceResultEither =
5238 toscaOperationFacade.getToscaElement(resourceId,
5241 if (resourceResultEither.isRight()) {
5242 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5243 log.debug("Failed to found resource with id {} ", resourceId);
5245 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5248 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5249 return Either.right(componentsUtils.getResponseFormatByResource(
5250 componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5253 Resource resource = resourceResultEither.left().value();
5254 if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
5255 ListUtils.emptyIfNull(resource.getInputs())
5256 .forEach(input -> input.setConstraints(setInputConstraint(input)));
5259 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5260 dataParamsToReturn);
5261 return Either.left(dataTransfer);
5265 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5266 Resource resource = (Resource) clonedComponent;
5267 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5268 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5269 .shouldUpgradeToLatestDerived(resource);
5270 if (shouldUpgradeToLatestDerived.isRight()) {
5271 return Either.right(
5272 componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5274 return Either.left(shouldUpgradeToLatestDerived.left().value());
5276 return super.shouldUpgradeToLatestDerived(clonedComponent);