2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
24 import fj.data.Either;
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
31 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
32 import org.openecomp.sdc.be.components.csar.CsarInfo;
33 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
34 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
36 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
37 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
39 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
40 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
41 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
42 import org.openecomp.sdc.be.config.BeEcompErrorManager;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
44 import org.openecomp.sdc.be.config.ConfigurationManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
47 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
48 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
49 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
50 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
57 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
59 import org.openecomp.sdc.be.impl.ComponentsUtils;
60 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
61 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
62 import org.openecomp.sdc.be.model.*;
63 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
64 import org.openecomp.sdc.be.model.category.CategoryDefinition;
65 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
66 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
67 import org.openecomp.sdc.be.model.operations.StorageException;
68 import org.openecomp.sdc.be.model.operations.api.*;
69 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
70 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
71 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
72 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
73 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
74 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
75 import org.openecomp.sdc.be.tosca.CsarUtils;
76 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
77 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
78 import org.openecomp.sdc.be.user.IUserBusinessLogic;
79 import org.openecomp.sdc.be.user.UserBusinessLogic;
80 import org.openecomp.sdc.be.utils.CommonBeUtils;
81 import org.openecomp.sdc.be.utils.TypeUtils;
82 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
83 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
84 import org.openecomp.sdc.common.api.Constants;
85 import org.openecomp.sdc.common.datastructure.Wrapper;
86 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
87 import org.openecomp.sdc.common.log.wrappers.Logger;
88 import org.openecomp.sdc.common.util.GeneralUtility;
89 import org.openecomp.sdc.common.util.ValidationUtils;
90 import org.openecomp.sdc.exception.ResponseFormat;
91 import org.springframework.beans.factory.annotation.Autowired;
92 import org.springframework.web.context.WebApplicationContext;
93 import org.yaml.snakeyaml.DumperOptions;
94 import org.yaml.snakeyaml.Yaml;
96 import javax.servlet.ServletContext;
98 import java.util.Map.Entry;
99 import java.util.function.Function;
100 import java.util.regex.Pattern;
102 import static java.util.stream.Collectors.*;
103 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
104 import static org.apache.commons.collections.MapUtils.isEmpty;
105 import static org.apache.commons.collections.MapUtils.isNotEmpty;
106 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
107 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
108 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
110 @org.springframework.stereotype.Component("resourceBusinessLogic")
111 public class ResourceBusinessLogic extends ComponentBusinessLogic {
113 private static final String DELETE_RESOURCE = "Delete Resource";
114 private static final String IN_RESOURCE = " in resource {} ";
115 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
116 public static final String INITIAL_VERSION = "0.1";
117 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
118 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
119 private static final String CREATE_RESOURCE = "Create Resource";
120 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
121 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
122 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
123 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
124 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
127 * Default constructor
129 public ResourceBusinessLogic() {
130 log.debug("ResourceBusinessLogic started");
134 private ICapabilityTypeOperation capabilityTypeOperation = null;
137 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
140 private LifecycleBusinessLogic lifecycleBusinessLogic;
143 private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
146 private ResourceImportManager resourceImportManager;
149 private InputsBusinessLogic inputsBusinessLogic;
152 private CompositionBusinessLogic compositionBusinessLogic;
155 private ICacheMangerOperation cacheManagerOperation;
158 private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
161 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
164 private MergeInstanceUtils mergeInstanceUtils;
167 private UiComponentDataConverter uiComponentDataConverter;
170 private CsarBusinessLogic csarBusinessLogic;
172 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
173 return lifecycleBusinessLogic;
176 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
177 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
180 public IElementOperation getElementDao() {
184 public void setElementDao(IElementOperation elementDao) {
185 this.elementDao = elementDao;
188 public IUserBusinessLogic getUserAdmin() {
189 return this.userAdmin;
192 public void setUserAdmin(UserBusinessLogic userAdmin) {
193 this.userAdmin = userAdmin;
196 public ComponentsUtils getComponentsUtils() {
197 return this.componentsUtils;
200 public void setComponentsUtils(ComponentsUtils componentsUtils) {
201 this.componentsUtils = componentsUtils;
204 public ArtifactsBusinessLogic getArtifactsManager() {
205 return artifactsBusinessLogic;
208 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
209 this.artifactsBusinessLogic = artifactsManager;
212 public ApplicationDataTypeCache getApplicationDataTypeCache() {
213 return applicationDataTypeCache;
216 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
217 this.applicationDataTypeCache = applicationDataTypeCache;
220 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
221 this.interfaceTypeOperation = interfaceTypeOperation;
225 * the method returns a list of all the resources that are certified, the
226 * returned resources are only abstract or only none abstract according to
233 public List<Resource> getAllCertifiedResources(boolean getAbstract,
234 HighestFilterEnum highestFilter, String userId) {
235 User user = validateUserExists(userId, "get All Certified Resources", false);
236 Boolean isHighest = null;
237 switch (highestFilter) {
243 case NON_HIGHEST_ONLY:
249 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
250 .getAllCertifiedResources(getAbstract, isHighest);
252 if (getResponse.isRight()) {
253 throw new StorageException(getResponse.right().value());
256 return getResponse.left().value();
259 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
260 ResourceTypeEnum resourceTypeEnum, String userId) {
262 validateUserExists(userId, "validate Resource Name Exists", false);
264 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
265 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
269 if (dataModelResponse.isLeft()) {
270 Map<String, Boolean> result = new HashMap<>();
271 result.put("isValid", dataModelResponse.left().value());
272 log.debug("validation was successfully performed.");
273 return Either.left(result);
276 ResponseFormat responseFormat = componentsUtils
277 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
279 return Either.right(responseFormat);
282 public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
283 User user, Map<String, byte[]> csarUIPayload, String payloadName) {
284 validateResourceBeforeCreate(resource, user, false);
285 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
286 if (StringUtils.isNotEmpty(csarUUID)) {
287 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
288 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
289 return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
292 return createResourceByDao(resource, user, auditingAction, false, false);
295 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
296 Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
297 String csarUUID = payloadName;
298 String csarVersion = null;
299 Resource updatedResource = null;
300 if (payloadName == null) {
301 csarUUID = resource.getCsarUUID();
302 csarVersion = resource.getCsarVersion();
304 if (csarUUID != null && !csarUUID.isEmpty()) {
305 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
306 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
307 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
308 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
309 overrideImmutableMetadata(oldResource, resource);
311 validateResourceBeforeCreate(resource, user, false);
312 String oldCsarVersion = oldResource.getCsarVersion();
313 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
315 // (on boarding flow): If the update includes same csarUUID and
316 // same csarVersion as already in the VF - no need to import the
317 // csar (do only metadata changes if there are).
318 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
319 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
322 updatedResource = updateResourceFromCsar(oldResource, resource, user,
323 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
326 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
327 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
329 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
330 throw new ComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
332 return updatedResource;
335 private void validateCsarIsNotAlreadyUsed(Resource oldResource,
336 Resource resource, String csarUUID, User user) {
337 // (on boarding flow): If the update includes a csarUUID: verify this
338 // csarUUID is not in use by another VF, If it is - use same error as
340 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
341 // select another or update the existing VF." %1 - csarUUID, %2 - VF
343 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
344 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
345 if (resourceLinkedToCsarRes.isRight()) {
346 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
347 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
348 resource.getSystemName());
349 throw new StorageException(resourceLinkedToCsarRes.right().value());
351 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
352 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
353 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
354 resourceLinkedToCsarRes.left().value().getName());
355 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
356 throw new ComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
357 resourceLinkedToCsarRes.left().value().getName());
361 private void validateCsarUuidMatching(Resource resource,
362 Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
363 // (on boarding flow): If the update includes csarUUID which is
364 // different from the csarUUID of the VF - fail with
365 // error: "Error: Resource %1 cannot be updated using since it is linked
366 // to a different VSP" %1 - VF name
367 String oldCsarUUID = oldResource.getCsarUUID();
368 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
370 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
371 resourceUniqueId, csarUUID, oldCsarUUID);
372 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
373 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
374 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
375 throw new ComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
379 private Resource getResourceByUniqueId(String resourceUniqueId) {
380 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
381 if (oldResourceRes.isRight()) {
382 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
383 oldResourceRes.right().value());
384 throw new StorageException(oldResourceRes.right().value());
386 return oldResourceRes.left().value();
389 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
390 resource.setName(oldRresource.getName());
391 resource.setIcon(oldRresource.getIcon());
392 resource.setTags(oldRresource.getTags());
393 resource.setCategories(oldRresource.getCategories());
394 resource.setDerivedFrom(oldRresource.getDerivedFrom());
397 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
398 User user, AuditingActionEnum updateResource, boolean inTransaction,
399 Map<String, byte[]> csarUIPayload, String csarUUID) {
400 Resource updatedResource = null;
401 validateLifecycleState(oldResource, user);
402 String lockedResourceId = oldResource.getUniqueId();
403 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
404 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
405 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
406 "update Resource From Csar");
407 if (lockResult.isRight()) {
408 throw new ComponentException(lockResult.right().value());
411 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
413 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
414 nodeTypesInfo, csarInfo, oldResource);
415 if (findNodeTypesArtifactsToHandleRes.isRight()) {
416 log.debug("failed to find node types for update with artifacts during import csar {}. ",
417 csarInfo.getCsarUUID());
418 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
420 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
423 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
424 csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
426 connectUiRelations(oldResource, updatedResource);
428 } catch (ComponentException|StorageException e){
429 rollback(inTransaction, newResource, createdArtifacts, null);
434 log.debug("unlock resource {}", lockedResourceId);
435 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
437 return updatedResource;
441 private void validateLifecycleState(Resource oldResource, User user) {
442 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
443 !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
444 log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
445 oldResource.getLastUpdaterUserId(), user.getUserId());
446 throw new ComponentException(ActionStatus.RESTRICTED_OPERATION);
450 private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
451 Either<Resource, ResponseFormat> result;
453 List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
455 StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
456 if (status == StorageOperationStatus.OK) {
457 newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
458 result = Either.left(newResource);
460 result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
466 private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
467 AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
468 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
469 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
470 String nodeName, boolean isNested) {
471 boolean inTransaction = true;
472 boolean shouldLock = false;
473 Resource preparedResource = null;
474 ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
476 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
477 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
478 preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
479 inTransaction, shouldLock, isNested).left;
480 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
481 handleResourceGenericType(preparedResource);
482 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
483 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
484 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
485 preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
486 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
487 } catch (ComponentException e) {
488 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
489 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
490 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
492 } catch (StorageException e){
493 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
494 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
495 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
498 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
499 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
500 preparedResource.getSystemName());
501 if (validateUpdateVfGroupNamesRes.isRight()) {
503 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
505 // add groups to resource
506 Map<String, GroupDefinition> groups;
508 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
509 groups = validateUpdateVfGroupNamesRes.left().value();
511 groups = uploadComponentInstanceInfoMap.getGroups();
513 handleGroupsProperties(preparedResource, groups);
514 preparedResource = updateGroupsOnResource(preparedResource, groups);
515 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
516 nodeTypesArtifactsToHandle);
518 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
519 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
520 if (updateArtifactsEither.isRight()) {
521 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
522 throw new ComponentException(updateArtifactsEither.right().value());
524 preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
526 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
527 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
528 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
530 throw new ComponentException(responseFormat);
532 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
533 return preparedResource;
536 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
537 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
538 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
540 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
541 Resource resource = preparedResource;
543 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
544 .getNodeTypesArtifactsToHandle();
545 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
546 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
547 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
548 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
549 if (handleNodeTypeArtifactsRes.isRight()) {
550 return Either.right(handleNodeTypeArtifactsRes.right().value());
554 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
555 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
556 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
557 if (createdCsarArtifactsEither.isRight()) {
558 return createdCsarArtifactsEither;
561 resource = createdCsarArtifactsEither.left().value();
563 return Either.left(resource);
566 private Resource handleResourceGenericType(Resource resource) {
567 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
568 if (resource.shouldGenerateInputs()) {
569 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
571 return genericResource;
574 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
575 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
577 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
578 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
579 = Either.left(nodeTypesArtifactsToHandle);
582 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
583 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
584 extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
585 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
586 oldResource.getName(), csarInfo.getCsarUUID());
587 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
588 extractedVfcsArtifacts,
589 namespace, vfcToscaNames));
590 } catch (Exception e) {
591 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
592 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
593 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
595 return nodeTypesArtifactsToHandleRes;
598 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
599 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
601 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
602 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
603 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
604 if (!isEmpty(extractedVfcsArtifacts)) {
605 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
606 if (extractedVfcsArtifacts.containsKey(namespace)) {
607 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
609 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
610 } else if (curNodeType != null) {
611 // delete all artifacts if have not received artifacts from
613 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
614 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
615 // delete all informational artifacts
616 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
617 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
619 // delete all deployment artifacts
620 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
621 if (!artifactsToDelete.isEmpty()) {
622 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
625 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
626 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
630 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
631 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
632 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
633 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
634 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
635 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
636 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
637 return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
639 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
644 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
645 Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
647 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
649 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
650 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
651 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
652 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
653 collectExistingArtifacts(curNodeType));
654 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
655 } catch (Exception e) {
656 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
657 throw new ComponentException(ActionStatus.GENERAL_ERROR);
659 return nodeTypeArtifactsToHandle;
662 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
663 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
664 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
665 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
666 if (!artifactsToUpload.isEmpty()) {
667 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
669 if (!artifactsToUpdate.isEmpty()) {
670 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
672 if (!artifactsToDelete.isEmpty()) {
673 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
676 return nodeTypeArtifactsToHandle;
679 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
680 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
681 Map<String, ArtifactDefinition> existingArtifacts) {
682 if (!existingArtifacts.isEmpty()) {
683 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
684 artifactsToDelete.addAll(existingArtifacts.values());
688 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
689 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
691 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
693 if (foundArtifact.isPresent()) {
694 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
695 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
696 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
697 artifactsToUpload.remove(currNewArtifact);
699 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
700 throw new ComponentException(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
701 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
702 foundArtifact.get().getArtifactType());
707 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
708 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
709 foundArtifact.setPayload(currNewArtifact.getPayloadData());
710 foundArtifact.setPayloadData(
711 Base64.encodeBase64String(currNewArtifact.getPayloadData()));
712 foundArtifact.setArtifactChecksum(GeneralUtility
713 .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
714 artifactsToUpdate.add(foundArtifact);
718 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
719 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
720 if (curNodeType == null) {
721 return existingArtifacts;
723 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
724 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
726 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
728 .putAll(curNodeType.getArtifacts().entrySet()
730 .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
731 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
733 return existingArtifacts;
737 * Changes resource life cycle state to checked out
741 * @param inTransaction
744 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
745 Either<Resource, ResponseFormat> checkoutResourceRes;
747 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
748 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
750 "************* Going to change life cycle state of resource {} to not certified checked out. ",
752 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
753 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
754 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
755 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
756 inTransaction, true);
757 if (checkoutRes.isRight()) {
758 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
759 resource.getComponentType().getNodeType(), resource.getUniqueId(),
760 checkoutRes.right().value().getStatus());
761 checkoutResourceRes = Either.right(checkoutRes.right().value());
763 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
766 checkoutResourceRes = Either.left(resource);
768 } catch (Exception e) {
769 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
770 checkoutResourceRes = Either.right(responseFormat);
771 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
774 return checkoutResourceRes;
778 * Handles Artifacts of NodeType
780 * @param nodeTypeResource
781 * @param nodeTypeArtifactsToHandle
783 * @param inTransaction
786 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
787 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
788 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
789 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
790 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
791 Either<Resource, ResponseFormat> changeStateResponse;
793 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
794 if (changeStateResponse.isRight()) {
795 return Either.right(changeStateResponse.right().value());
797 nodeTypeResource = changeStateResponse.left().value();
799 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
800 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
801 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
803 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
804 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
805 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
806 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
807 nodeTypeResource.getName());
808 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
809 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
810 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
811 ignoreLifecycleState, curOperation),
812 false, inTransaction);
813 if (handleNodeTypeArtifactsRequestRes.isRight()) {
814 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
817 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
818 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
820 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
823 if (handleNodeTypeArtifactsRes == null) {
824 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
826 } catch (Exception e) {
827 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
828 handleNodeTypeArtifactsRes = Either.right(responseFormat);
829 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
831 return handleNodeTypeArtifactsRes;
834 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
835 String vfResourceName, CsarInfo csarInfo) {
836 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
838 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
839 if (!nodes.isEmpty()) {
840 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
841 while (nodesNameEntry.hasNext()) {
842 Entry<String, Object> nodeType = nodesNameEntry.next();
843 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
844 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
845 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
848 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
849 vfcToscaNames.put(cvfc.getType(),
850 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
852 return vfcToscaNames;
855 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
856 Map<String, Object> nodes = new HashMap<>();
857 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
858 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
860 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
864 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
865 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
866 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
867 if (eitherNodeTypes.isLeft()) {
868 nodes.putAll(eitherNodeTypes.left().value());
872 public Resource createResourceFromCsar(Resource resource, User user,
873 Map<String, byte[]> csarUIPayload, String csarUUID) {
874 log.trace("************* created successfully from YAML, resource TOSCA ");
876 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
878 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
879 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
880 nodeTypesInfo, csarInfo, resource);
881 if (findNodeTypesArtifactsToHandleRes.isRight()) {
882 log.debug("failed to find node types for update with artifacts during import csar {}. ",
883 csarInfo.getCsarUUID());
884 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
886 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
887 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
889 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
890 vfResource.getToscaResourceName());
894 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
895 log.trace("validating resource before create");
896 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
897 // validate user role
898 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
899 // VF / PNF "derivedFrom" should be null (or ignored)
900 if (ModelConverter.isAtomicComponent(resource)) {
901 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
903 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
907 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
908 // nodeTypesArtifactsToCreate, true, false, null
909 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
910 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
911 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
912 boolean shouldLock, boolean inTransaction, String nodeName) {
914 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
915 Resource createdResource;
917 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
918 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
919 createdResource = createResourceAndRIsFromYaml(yamlName, resource,
920 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
921 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
922 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
923 } catch (ComponentException e) {
924 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
925 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
927 } catch (StorageException e){
928 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
929 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
932 return createdResource;
936 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
937 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
938 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
941 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
942 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
943 if (toscaVersion.isRight()) {
944 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
946 Map<String, Object> mapToConvert = new HashMap<>();
947 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
948 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
949 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
950 return csarInfo.getCreatedNodes();
953 private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
954 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
955 .left().orValue(HashMap::new);
958 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) {
959 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
960 Resource vfcCreated = null;
961 while (nodesNameValueIter.hasNext()) {
962 Entry<String, Object> nodeType = nodesNameValueIter.next();
963 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
964 || nodeTypesArtifactsToHandle.isEmpty() ? null
965 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
967 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
968 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
969 vfcCreated = handleNestedVfc(resource,
970 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
972 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
973 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
974 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
975 log.trace("************* Going to create node {}", nodeType.getKey());
976 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
977 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
979 log.debug("************* Finished to create node {}", nodeType.getKey());
981 vfcCreated = resourceCreated.getLeft();
982 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
983 vfcCreated.getToscaResourceName());
985 if (vfcCreated != null) {
986 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
988 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
992 private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
993 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
996 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
997 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
999 log.debug("************* Going to create node types from yaml {}", yamlName);
1000 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
1001 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1002 log.debug("************* Finished to create node types from yaml {}", yamlName);
1004 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1005 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1006 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1007 csarInfo, nodeName, yamlName);
1012 private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1013 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1014 String nodeName, String yamlName) {
1016 Resource oldComplexVfc = null;
1017 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1018 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1019 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1020 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1021 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1022 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1023 nodeName).getRight());
1025 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1026 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1027 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1028 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1029 } else if (oldComplexVfcRes.isLeft()) {
1030 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1031 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1032 oldComplexVfcRes.left().value(), newComplexVfc,
1033 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1034 if (eitherValidation.isLeft()) {
1035 oldComplexVfc = oldComplexVfcRes.left().value();
1038 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1039 oldComplexVfc, newComplexVfc);
1040 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1041 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1042 CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1043 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1044 Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1046 if (result.isRight()) {
1047 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1049 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1050 csarInfo.removeNodeFromQueue();
1051 return result.left().value();
1054 private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1055 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1056 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1058 Resource handleComplexVfcRes;
1059 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1060 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1061 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1062 .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
1063 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1064 if (oldComplexVfc == null) {
1065 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1066 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1068 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1069 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1070 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1072 return handleComplexVfcRes;
1075 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1076 Map<String, NodeTypeInfo> nodesInfo) {
1078 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1079 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1080 csarInfo.addNodeToQueue(nodeName);
1081 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1082 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1085 private String getNodeTypeActualName(String fullName) {
1086 String nameWithouNamespacePrefix = fullName
1087 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1088 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1089 String resourceType = findTypes[0];
1090 return nameWithouNamespacePrefix.substring(resourceType.length());
1093 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1094 String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1095 Resource resourceVf, boolean needLock,
1096 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1097 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1100 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1102 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1103 resourceMetaData.getResourceType(), csarInfo);
1104 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1105 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1106 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1107 nodeNameValue.getKey(), isNested);
1110 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1111 String nodeResourceType, CsarInfo csarInfo) {
1112 // We need to create a Yaml from each node_types in order to create
1113 // resource from each node type using import normative flow.
1114 DumperOptions options = new DumperOptions();
1115 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1116 Yaml yaml = new Yaml(options);
1118 Map<String, Object> node = new HashMap<>();
1119 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1120 .getLeft(), nodeNameValue.getValue());
1121 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1123 return yaml.dumpAsMap(mapToConvert);
1126 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1127 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1128 return Either.left(true);
1131 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1132 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1133 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1134 String nodeName, boolean isNested) {
1136 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1137 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1138 Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1139 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1140 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1141 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
1142 .left().on(this::failOnCertification);
1145 private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
1146 throw new ComponentException(error);
1149 private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1150 String nodeName, User user) {
1151 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1153 // validate nodetype name prefix
1154 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1155 log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1156 Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1157 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1158 yamlName, resourceMetaData.getName(), nodeName);
1161 String actualName = this.getNodeTypeActualName(nodeName);
1162 String namePrefix = nodeName.replace(actualName, "");
1163 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1165 // if we import from csar, the node_type name can be
1166 // org.openecomp.resource.abstract.node_name - in this case we always
1168 if (resourceType.equals(Constants.ABSTRACT)) {
1169 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1172 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1173 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1174 ResourceTypeEnum.values());
1175 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1176 yamlName, resourceMetaData.getName(), nodeName);
1180 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1182 // Setting type from name
1183 String type = resourceType.toUpperCase();
1184 resourceMetaData.setResourceType(type);
1186 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1187 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1188 resourceMetaData.setContactId(user.getUserId());
1189 resourceMetaData.setVendorName(resourceVf.getVendorName());
1190 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1193 List<String> tags = new ArrayList<>();
1194 tags.add(resourceMetaData.getName());
1195 resourceMetaData.setTags(tags);
1198 CategoryDefinition category = new CategoryDefinition();
1199 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1200 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1201 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1202 category.addSubCategory(subCategory);
1203 List<CategoryDefinition> categories = new ArrayList<>();
1204 categories.add(category);
1205 resourceMetaData.setCategories(categories);
1207 return resourceMetaData;
1210 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1211 Map<String, NodeTypeInfo> nodesInfo) {
1212 Resource cvfc = new Resource();
1213 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1214 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1215 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1216 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1217 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1218 cvfc.setAbstract(true);
1219 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1220 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1221 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1222 cvfc.setContactId(csarInfo.getModifier().getUserId());
1223 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1224 cvfc.setVendorName(resourceVf.getVendorName());
1225 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1226 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1227 cvfc.setToscaResourceName(
1228 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1230 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1232 List<String> tags = new ArrayList<>();
1233 tags.add(cvfc.getName());
1236 CategoryDefinition category = new CategoryDefinition();
1237 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1238 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1239 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1240 category.addSubCategory(subCategory);
1241 List<CategoryDefinition> categories = new ArrayList<>();
1242 categories.add(category);
1243 cvfc.setCategories(categories);
1245 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1246 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1247 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1252 private String buildCvfcName(String resourceVfName, String nodeName) {
1253 String nameWithouNamespacePrefix = nodeName
1254 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1255 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1256 String resourceType = findTypes[0];
1257 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1258 return addCvfcSuffixToResourceName(resourceName);
1261 private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
1262 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1263 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1264 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1265 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1266 boolean shouldLock, boolean inTransaction, String nodeName) {
1268 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1271 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1273 if (lockResult.isRight()) {
1274 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1275 throw new ComponentException(lockResult.right().value());
1277 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1280 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1281 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1282 resource = createResourceTransaction(resource,
1283 csarInfo.getModifier(), isNormative);
1284 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1285 log.trace("************* Going to add inputs from yaml {}", yamlName);
1286 if (resource.shouldGenerateInputs())
1287 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1289 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1290 resource = createInputsOnResource(resource, inputs);
1291 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1293 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1295 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1297 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1298 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1299 nodeTypesArtifactsToCreate, nodeName);
1300 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1301 // validate update vf module group names
1302 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1303 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1304 if (validateUpdateVfGroupNamesRes.isRight()) {
1305 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1306 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
1308 // add groups to resource
1309 Map<String, GroupDefinition> groups;
1310 log.trace("************* Going to add groups from yaml {}", yamlName);
1312 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1313 groups = validateUpdateVfGroupNamesRes.left().value();
1315 groups = parsedToscaYamlInfo.getGroups();
1318 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1320 if (createGroupsOnResource.isRight()) {
1321 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1322 throw new ComponentException(createGroupsOnResource.right().value());
1324 resource = createGroupsOnResource.left().value();
1325 log.trace("************* Finished to add groups from yaml {}", yamlName);
1327 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1329 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1330 nodeTypesArtifactsToCreate);
1332 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1333 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1334 if (createArtifactsEither.isRight()) {
1335 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1336 throw new ComponentException(createArtifactsEither.right().value());
1339 resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
1341 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1342 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1343 ASDCKpiApi.countCreatedResourcesKPI();
1346 } catch(ComponentException|StorageException e) {
1347 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1350 if (!inTransaction) {
1354 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1355 NodeTypeEnum.Resource);
1360 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1361 if(!inTransaction) {
1362 titanDao.rollback();
1364 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1365 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1366 log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
1370 private Resource getResourceWithGroups(String resourceId) {
1372 ComponentParametersView filter = new ComponentParametersView();
1373 filter.setIgnoreGroups(false);
1374 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
1375 if (updatedResource.isRight()) {
1376 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
1378 return updatedResource.left().value();
1381 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1382 Map<String, GroupDefinition> groups) {
1383 if (groups != null && !groups.isEmpty()) {
1384 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
1386 handleGroupsProperties(resource, groups);
1387 fillGroupsFinalFields(groupsAsList);
1388 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1389 groupsAsList, true);
1390 if (createGroups.isRight()) {
1391 return Either.right(createGroups.right().value());
1394 return Either.left(resource);
1396 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1397 .getToscaElement(resource.getUniqueId());
1398 if (updatedResource.isRight()) {
1399 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1400 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1401 return Either.right(responseFormat);
1403 return Either.left(updatedResource.left().value());
1406 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1407 List<InputDefinition> inputs = resource.getInputs();
1408 if (MapUtils.isNotEmpty(groups)) {
1411 .filter(g -> isNotEmpty(g.getProperties()))
1412 .flatMap(g -> g.getProperties().stream())
1413 .forEach(p -> handleGetInputs(p, inputs));
1417 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1418 if (isNotEmpty(property.getGetInputValues())) {
1419 if (inputs == null || inputs.isEmpty()) {
1420 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1421 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1423 .map(GetInputValueDataDefinition::getInputName)
1424 .collect(toList()).toString());
1426 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1427 while (getInputValuesIter.hasNext()) {
1428 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1429 InputDefinition input = findInputByName(inputs, getInput);
1430 getInput.setInputId(input.getUniqueId());
1431 if (getInput.getGetInputIndex() != null) {
1432 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1433 input = findInputByName(inputs, getInputIndex);
1434 getInputIndex.setInputId(input.getUniqueId());
1435 getInputValuesIter.add(getInputIndex);
1441 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1442 Optional<InputDefinition> inputOpt = inputs.stream()
1443 .filter(p -> p.getName().equals(getInput.getInputName()))
1445 if (!inputOpt.isPresent()) {
1446 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1447 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1449 return inputOpt.get();
1452 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1453 groupsAsList.forEach(groupDefinition -> {
1454 groupDefinition.setInvariantName(groupDefinition.getName());
1455 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1459 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1460 if (isEmpty(groups)) {
1463 updateOrCreateGroups(resource, groups);
1465 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1466 .getToscaElement(resource.getUniqueId());
1467 if (updatedResource.isRight()) {
1468 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1469 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1471 return updatedResource.left().value();
1474 private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1475 List<GroupDefinition> groupsFromResource = resource.getGroups();
1476 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1477 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1478 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1479 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1480 if (isNotEmpty(groupsFromResource)) {
1481 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1482 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1484 groupsToCreate.addAll(groupsAsList);
1486 if (isNotEmpty(groupsToCreate)) {
1487 fillGroupsFinalFields(groupsToCreate);
1488 if (isNotEmpty(groupsFromResource)) {
1489 groupBusinessLogic.addGroups(resource,
1490 groupsToCreate, true)
1492 .on(this::throwComponentException);
1494 groupBusinessLogic.createGroups(resource,
1495 groupsToCreate, true)
1497 .on(this::throwComponentException);
1500 if (isNotEmpty(groupsToDelete)) {
1501 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1503 .on(this::throwComponentException);
1505 if (isNotEmpty(groupsToUpdate)) {
1506 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1508 .on(this::throwComponentException);
1512 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1513 for (GroupDefinition group : groupsFromResource) {
1514 Optional<GroupDefinition> op = groupsAsList.stream()
1515 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1516 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1517 groupsToDelete.add(group);
1522 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1523 for (GroupDefinition group : groupsAsList) {
1524 Optional<GroupDefinition> op = groupsFromResource.stream()
1525 .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1526 if (op.isPresent()) {
1527 GroupDefinition groupToUpdate = op.get();
1528 groupToUpdate.setMembers(group.getMembers());
1529 groupToUpdate.setCapabilities(group.getCapabilities());
1530 groupToUpdate.setProperties(group.getProperties());
1531 groupsToUpdate.add(groupToUpdate);
1533 groupsToCreate.add(group);
1538 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1539 List<InputDefinition> resourceProperties = resource.getInputs();
1540 if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1542 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1544 if (createInputs.isRight()) {
1545 throw new ComponentException(createInputs.right().value());
1550 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1551 .getToscaElement(resource.getUniqueId());
1552 if (updatedResource.isRight()) {
1553 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1554 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1556 return updatedResource.left().value();
1559 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1561 List<GroupDefinition> result = new ArrayList<>();
1562 List<ComponentInstance> componentInstances = component.getComponentInstances();
1564 if (groups != null) {
1565 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1566 if (validateCyclicGroupsDependencies.isRight()) {
1567 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1569 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1570 String groupName = entry.getKey();
1571 GroupDefinition groupDefinition = entry.getValue();
1572 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1573 updatedGroupDefinition.setMembers(null);
1574 Map<String, String> members = groupDefinition.getMembers();
1575 if (members != null) {
1576 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1578 result.add(updatedGroupDefinition);
1584 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1585 Set<String> compInstancesNames = members.keySet();
1587 if (CollectionUtils.isEmpty(componentInstances)) {
1588 String membersAstString = compInstancesNames.stream().collect(joining(","));
1589 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1590 membersAstString, groupName, component.getNormalizedName());
1591 throw new ComponentException(componentsUtils.getResponseFormat(
1592 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1593 component.getNormalizedName(), getComponentTypeForResponse(component)));
1595 // Find all component instances with the member names
1596 Map<String, String> memberNames = componentInstances.stream()
1597 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1598 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1599 Map<String, String> relevantInstances = memberNames.entrySet().stream()
1600 .filter(n -> compInstancesNames.contains(n.getKey()))
1601 .collect(toMap(Entry::getKey, Entry::getValue));
1603 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1605 List<String> foundMembers = new ArrayList<>();
1606 if (relevantInstances != null) {
1607 foundMembers = relevantInstances.keySet().stream().collect(toList());
1609 compInstancesNames.removeAll(foundMembers);
1610 String membersAstString = compInstancesNames.stream().collect(joining(","));
1611 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1612 groupName, component.getNormalizedName());
1613 throw new ComponentException(componentsUtils.getResponseFormat(
1614 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1615 component.getNormalizedName(), getComponentTypeForResponse(component)));
1617 updatedGroupDefinition.setMembers(relevantInstances);
1621 * This Method validates that there is no cyclic group dependencies. meaning
1622 * group A as member in group B which is member in group A
1627 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1629 Either<Boolean, ResponseFormat> result = Either.left(true);
1631 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1632 while (allGroupsItr.hasNext() && result.isLeft()) {
1633 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1634 // Fetches a group member A
1635 String groupAName = groupAEntry.getKey();
1636 // Finds all group members in group A
1637 Set<String> allGroupAMembersNames = new HashSet<>();
1638 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1639 // If A is a group member of itself found cyclic dependency
1640 if (allGroupAMembersNames.contains(groupAName)) {
1641 ResponseFormat responseFormat = componentsUtils
1642 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1643 result = Either.right(responseFormat);
1646 } catch (Exception e) {
1647 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1648 result = Either.right(responseFormat);
1649 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1655 * This Method fills recursively the set groupMembers with all the members
1656 * of the given group which are also of type group.
1660 * @param allGroupMembers
1663 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1664 Set<String> allGroupMembers) {
1666 // Found Cyclic dependency
1667 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1670 GroupDefinition groupDefinition = allGroups.get(groupName);
1671 // All Members Of Current Group Resource Instances & Other Groups
1672 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1673 // Filtered Members Of Current Group containing only members which
1675 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1676 // Keep Only Elements of type group and not Resource Instances
1677 filter(allGroups::containsKey).
1678 // Add Filtered Elements to main Set
1679 peek(allGroupMembers::add).
1683 // Recursively call the method for all the filtered group members
1684 for (String innerGroupName : currGroupFilteredMembers) {
1685 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1690 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
1691 Set<String> allGroupMembers) {
1693 boolean stop = false;
1694 // In Case Not Group Stop
1695 if (!allGroups.containsKey(groupName)) {
1698 // In Case Group Has no members stop
1700 GroupDefinition groupDefinition = allGroups.get(groupName);
1701 stop = isEmpty(groupDefinition.getMembers());
1704 // In Case all group members already contained stop
1706 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1707 Set<String> membersOfTypeGroup = allMembers.stream().
1708 // Filter In Only Group members
1709 filter(allGroups::containsKey).
1712 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1717 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1718 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1719 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1720 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1721 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1724 log.debug("************* Going to create all nodes {}", yamlName);
1725 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1726 nodeTypesInfo, csarInfo, nodeName);
1727 log.debug("************* Finished to create all nodes {}", yamlName);
1728 log.debug("************* Going to create all resource instances {}", yamlName);
1729 resource = createResourceInstances(yamlName, resource,
1730 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1731 log.debug("************* Finished to create all resource instances {}", yamlName);
1732 log.debug("************* Going to create all relations {}", yamlName);
1733 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1734 log.debug("************* Finished to create all relations {}", yamlName);
1735 log.debug("************* Going to create positions {}", yamlName);
1736 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1737 log.debug("************* Finished to set positions {}", yamlName);
1741 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
1742 List<ArtifactDefinition> artifactsToAdd) {
1743 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
1745 artifactsToAdd.stream().forEach(a -> {
1746 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1747 vfcArtifacts.add(a);
1749 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1755 @SuppressWarnings("unchecked")
1756 private void handleNodeTypes(String yamlName, Resource resource,
1757 String topologyTemplateYaml, boolean needLock,
1758 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1759 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1760 CsarInfo csarInfo, String nodeName) {
1762 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1763 if (nodeTypeEntry.getValue().isNested()) {
1765 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1766 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1767 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1770 Map<String, Object> mappedToscaTemplate = null;
1771 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
1772 && nodeTypesInfo.containsKey(nodeName)) {
1773 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1775 if (isEmpty(mappedToscaTemplate)) {
1776 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1778 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1779 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1780 } catch(ComponentException e){
1781 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
1782 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1783 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1785 } catch (StorageException e){
1786 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1787 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1790 // add the created node types to the cache although they are not in the
1792 csarInfo.getCreatedNodes().values().stream()
1793 .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1796 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
1797 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1798 boolean inTransaction) {
1800 if (csarInfo.getCsar() != null) {
1801 String vendorLicenseModelId = null;
1802 String vfLicenseModelId = null;
1804 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1805 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1806 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1807 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1808 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1809 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1811 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1812 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1818 // Specific Behavior for license artifacts
1819 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1820 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
1821 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1822 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
1823 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
1825 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1826 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1827 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1828 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
1829 artifactOperation, null, true, shouldLock, inTransaction);
1831 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
1832 createdArtifacts, shouldLock, inTransaction, artifactOperation);
1833 if (eitherCreateResult.isRight()) {
1834 return Either.right(eitherCreateResult.right().value());
1836 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1837 .getToscaElement(resource.getUniqueId());
1838 if (eitherGerResource.isRight()) {
1839 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1840 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1842 return Either.right(responseFormat);
1845 resource = eitherGerResource.left().value();
1847 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1849 if (artifacsMetaCsarStatus.isLeft()) {
1850 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1851 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1852 Either<Resource, ResponseFormat> createArtifactsFromCsar;
1853 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1854 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1856 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1859 if (createArtifactsFromCsar.isRight()) {
1860 log.debug("Couldn't create artifacts from artifacts.meta");
1861 return Either.right(createArtifactsFromCsar.right().value());
1864 return Either.left(createArtifactsFromCsar.left().value());
1867 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
1871 return Either.left(resource);
1875 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
1876 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1877 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1878 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1879 boolean inTransaction) {
1880 byte[] artifactFileBytes = null;
1882 if (csarInfo.getCsar().containsKey(artifactPath)) {
1883 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1885 Either<Boolean, ResponseFormat> result = Either.left(true);
1886 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
1887 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1888 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
1889 shouldLock, inTransaction);
1890 if (handleDelete.isRight()) {
1891 result = Either.right(handleDelete.right().value());
1897 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1898 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1899 ArtifactOperationEnum.CREATE);
1903 if (artifactFileBytes != null) {
1904 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1905 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1906 artifactFileBytes, null, isFromCsar);
1907 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1908 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1909 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1910 if (eitherNonMetaArtifacts.isRight()) {
1911 BeEcompErrorManager.getInstance()
1912 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1913 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1914 ErrorSeverity.WARNING);
1915 return Either.right(eitherNonMetaArtifacts.right().value());
1921 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
1922 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
1926 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
1927 List<ArtifactDefinition> createdArtifacts,
1928 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
1929 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
1930 && eitherNonMetaArtifacts.isLeft()) {
1931 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
1932 if (eitherResult.isLeft()) {
1933 createdArtifacts.add(eitherResult.left().value());
1939 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
1940 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
1941 ArtifactOperationInfo artifactOperation) {
1943 Either<Resource, ResponseFormat> resStatus = null;
1944 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
1947 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
1948 if (artifactPathAndNameList.isRight()) {
1949 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
1950 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
1952 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
1954 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1955 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
1956 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
1958 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
1959 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
1961 if (findVfCsarArtifactsToHandleRes.isRight()) {
1962 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
1964 if (resStatus == null) {
1965 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
1968 if (resStatus == null && vfCsarArtifactsToHandle != null) {
1969 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
1971 if (resStatus == null) {
1972 resStatus = Either.left(resource);
1974 } catch (Exception e) {
1975 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1976 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
1978 CsarUtils.handleWarningMessages(collectedWarningMessages);
1983 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) {
1984 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
1987 Optional<ResponseFormat> optionalCreateInDBError =
1988 // Stream of artifacts to be created
1989 currArtifactOperationPair.getValue().stream()
1990 // create each artifact
1991 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
1992 e.getArtifactName(), e.getArtifactType().getType(),
1993 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
1994 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
1995 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1996 currArtifactOperationPair.getKey()),
1997 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
1998 // filter in only error
1999 .filter(Either::isRight).
2000 // Convert the error from either to
2002 map(e -> e.right().value()).
2003 // Check if an error occurred
2005 // Error found on artifact Creation
2006 if (optionalCreateInDBError.isPresent()) {
2007 resStatus = Either.right(optionalCreateInDBError.get());
2014 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
2015 List<NonMetaArtifactInfo> artifactPathAndNameList =
2016 // Stream of file paths contained in csar
2017 csarInfo.getCsar().entrySet().stream()
2018 // Filter in only VF artifact path location
2019 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2021 // Validate and add warnings
2022 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2023 collectedWarningMessages))
2024 // Filter in Non Warnings
2025 .filter(Either::isLeft)
2026 // Convert from Either to NonMetaArtifactInfo
2027 .map(e -> e.left().value())
2030 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2031 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2032 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2033 return Either.right(nonMetaArtifactInfo.getArtifactName());
2036 return Either.left(artifactPathAndNameList);
2039 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2040 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2042 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2043 // collect all Deployment and Informational artifacts of VF
2044 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2045 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2047 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2048 existingArtifacts.addAll(resource.getArtifacts().values());
2050 existingArtifacts = existingArtifacts.stream()
2051 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2052 // was created from HEAT.meta
2053 .filter(this::isNonMetaArtifact).collect(toList());
2055 List<String> artifactsToIgnore = new ArrayList<>();
2056 // collect IDs of Artifacts of VF which belongs to any group
2057 if (resource.getGroups() != null) {
2058 resource.getGroups().stream().forEach(g -> {
2059 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
2060 artifactsToIgnore.addAll(g.getArtifacts());
2064 existingArtifacts = existingArtifacts.stream()
2065 // filter artifacts which belongs to any group
2066 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
2067 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2070 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2071 boolean result = true;
2072 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2078 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2079 boolean result = true;
2080 if (artifact.getArtifactType() == null
2081 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2082 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2088 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
2089 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2090 log.debug("#createResourceInstancesRelations - Going to create relations ");
2091 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2092 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) {
2093 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
2094 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations","No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2095 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
2097 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2098 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2099 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2100 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2101 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2102 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2103 Map<String, Resource> originCompMap = new HashMap<>();
2104 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2105 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2107 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2108 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2109 if (allDataTypes.isRight()) {
2110 TitanOperationStatus status = allDataTypes.right().value();
2111 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2112 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2113 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2114 DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
2117 Resource finalResource = resource;
2118 uploadResInstancesMap
2120 .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2121 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
2122 instArtifacts, instAttributes, originCompMap, instInputs, i));
2124 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2125 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2126 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2127 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2128 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2129 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2131 resource = getResourceAfterCreateRelations(resource);
2133 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2134 associateResourceInstances(yamlName, resource, relations);
2135 handleSubstitutionMappings(resource, uploadResInstancesMap);
2136 log.debug("************* in create relations, getResource start");
2137 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2138 log.debug("************* in create relations, getResource end");
2139 if (eitherGetResource.isRight()) {
2140 throw new ComponentException(componentsUtils.getResponseFormatByResource(
2141 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
2143 return eitherGetResource.left().value();
2146 private Resource getResourceAfterCreateRelations(Resource resource) {
2147 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2148 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2149 .getToscaElement(resource.getUniqueId(), parametersView);
2151 if (eitherGetResource.isRight()) {
2152 throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2154 return eitherGetResource.left().value();
2157 private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2158 StorageOperationStatus addArtToInst;
2159 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2160 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2161 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2163 throw new ComponentException(componentsUtils
2164 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2168 private ComponentParametersView getComponentFilterAfterCreateRelations() {
2169 ComponentParametersView parametersView = new ComponentParametersView();
2170 parametersView.disableAll();
2171 parametersView.setIgnoreComponentInstances(false);
2172 parametersView.setIgnoreComponentInstancesProperties(false);
2173 parametersView.setIgnoreCapabilities(false);
2174 parametersView.setIgnoreRequirements(false);
2175 parametersView.setIgnoreGroups(false);
2176 return parametersView;
2179 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
2180 StorageOperationStatus addArtToInst;
2181 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2182 resource.getUniqueId());
2183 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2184 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2186 throw new ComponentException(componentsUtils
2187 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2191 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2192 StorageOperationStatus addArtToInst;
2193 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2194 resource.getUniqueId());
2195 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2196 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2198 throw new ComponentException(componentsUtils
2199 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2203 private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2204 StorageOperationStatus addArtToInst;
2206 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
2207 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2208 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2209 throw new ComponentException(componentsUtils
2210 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2214 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2215 StorageOperationStatus addArtToInst = toscaOperationFacade
2216 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2217 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2218 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2219 throw new ComponentException(componentsUtils
2220 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2224 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2225 if (MapUtils.isNotEmpty(instInputs)) {
2226 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2227 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2228 if (addInputToInst.isRight()) {
2229 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2230 addInputToInst.right().value());
2231 throw new ComponentException(componentsUtils.getResponseFormat(
2232 componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2237 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2238 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2239 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2240 if (addPropToInst.isRight()) {
2241 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2242 addPropToInst.right().value());
2243 throw new ComponentException(componentsUtils.getResponseFormat(
2244 componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2248 private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2249 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2250 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2251 if (getResourceRes.isRight()) {
2252 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2253 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2254 throw new ComponentException(responseFormat);
2256 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2257 uploadResInstancesMap);
2258 if (getResourceRes.isRight()) {
2259 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2260 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2261 throw new ComponentException(responseFormat);
2266 private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2267 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2268 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2269 ComponentInstance currentCompInstance = null;
2270 for (ComponentInstance compInstance : componentInstancesList) {
2272 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2273 currentCompInstance = compInstance;
2278 if (currentCompInstance == null) {
2279 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2280 resource.getUniqueId());
2281 BeEcompErrorManager.getInstance().logInternalDataError(
2282 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2283 resource.getUniqueId(), ErrorSeverity.ERROR);
2284 ResponseFormat responseFormat = componentsUtils
2285 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2286 throw new ComponentException(responseFormat);
2289 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2290 if (addRelationToRiRes.getStatus() != 200) {
2291 throw new ComponentException(addRelationToRiRes);
2296 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) {
2297 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2298 .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
2300 if (!currentCompInstanceOpt.isPresent()) {
2301 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2302 resource.getUniqueId());
2303 BeEcompErrorManager.getInstance().logInternalDataError(
2304 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2305 resource.getUniqueId(), ErrorSeverity.ERROR);
2306 ResponseFormat responseFormat = componentsUtils
2307 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2308 throw new ComponentException(responseFormat);
2310 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2311 String resourceInstanceId = currentCompInstance.getUniqueId();
2312 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
2313 if (isNotEmpty(originResource.getRequirements())) {
2314 instRequirements.put(currentCompInstance, originResource.getRequirements());
2316 if (isNotEmpty(originResource.getCapabilities())) {
2317 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2318 currentCompInstance, originResource);
2320 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
2321 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2323 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2324 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2326 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2327 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2329 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2330 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2331 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
2332 if (addPropertiesValueToRiRes.getStatus() != 200) {
2333 throw new ComponentException(addPropertiesValueToRiRes);
2336 addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2337 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
2341 private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2342 Resource originResource;
2343 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2344 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2345 .getToscaFullElement(currentCompInstance.getComponentUid());
2346 if (getOriginResourceRes.isRight()) {
2347 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2348 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2349 getOriginResourceRes);
2350 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2351 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2352 throw new ComponentException(responseFormat);
2354 originResource = getOriginResourceRes.left().value();
2355 originCompMap.put(originResource.getUniqueId(), originResource);
2357 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2359 return originResource;
2362 private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2363 Map<String, List<CapabilityDefinition>> originCapabilities;
2364 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2365 originCapabilities = new HashMap<>();
2366 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2367 originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v));
2368 uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
2369 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2371 originCapabilities = originResource.getCapabilities();
2373 instCapabilties.put(currentCompInstance, originCapabilities);
2376 private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2377 originCapabilities.values().stream()
2378 .flatMap(Collection::stream)
2379 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2380 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2383 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2384 for (UploadCapInfo capability : capabilities) {
2385 if (isNotEmpty(capability.getProperties())) {
2386 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2387 .collect(toMap(UploadInfo::getName, p -> p)));
2392 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2393 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2395 originCapabilities.put(type, list);
2398 private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2399 Map<String, DataTypeDefinition> allDataTypes) {
2400 properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2403 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2404 Map<String, DataTypeDefinition> allDataTypes) {
2405 String value = null;
2406 List<GetInputValueDataDefinition> getInputs = null;
2407 boolean isValidate = true;
2408 if (null != propertyInfo && propertyInfo.getValue() != null) {
2409 getInputs = propertyInfo.getGet_input();
2410 isValidate = getInputs == null || getInputs.isEmpty();
2412 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2414 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2415 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2418 property.setValue(value);
2419 return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2422 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2423 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2424 Either<Resource, StorageOperationStatus> updateRes = null;
2425 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2426 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2427 StorageOperationStatus status = toscaOperationFacade
2428 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2429 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2431 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2432 resource.getUniqueId(), status);
2433 updateRes = Either.right(status);
2435 if (updateRes == null) {
2436 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2437 updatedInstCapabilities, updatedInstRequirements);
2438 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2439 resource.getUniqueId());
2440 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2442 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2443 resource.getUniqueId(), status);
2444 updateRes = Either.right(status);
2447 if (updateRes == null) {
2448 updateRes = Either.left(resource);
2453 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2454 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2455 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2456 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2458 componentInstances.stream().forEach(i -> {
2459 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2460 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2461 fillUpdatedInstRequirements(updatedInstRequirements, i,
2462 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2466 private void fillUpdatedInstRequirements(
2467 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2468 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2469 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2470 Set<String> updatedReqNames = new HashSet<>();
2471 if (isNotEmpty(requirementsNamesToUpdate)) {
2472 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2473 updatedRequirements.put(requirements.getKey(),
2474 requirements.getValue().stream()
2475 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2476 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2478 r.setParentName(r.getName());
2479 r.setName(requirementsNamesToUpdate.get(r.getName()));
2480 updatedReqNames.add(r.getName());
2482 }).collect(toList()));
2485 if (isNotEmpty(updatedRequirements)) {
2486 updatedInstRequirements.put(instance, updatedRequirements);
2490 private void fillUpdatedInstCapabilities(
2491 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2492 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2493 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2494 Set<String> updatedCapNames = new HashSet<>();
2495 if (isNotEmpty(capabilitiesNamesToUpdate)) {
2496 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2497 updatedCapabilities.put(requirements.getKey(),
2498 requirements.getValue().stream()
2499 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2500 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2502 c.setParentName(c.getName());
2503 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2504 updatedCapNames.add(c.getName());
2506 }).collect(toList()));
2509 if (isNotEmpty(updatedCapabilities)) {
2510 updatedInstCapabilties.put(instance, updatedCapabilities);
2514 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2515 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2516 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2518 ComponentInstance currentCompInstance = null;
2520 for (ComponentInstance compInstance : componentInstancesList) {
2522 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2523 currentCompInstance = compInstance;
2529 if (currentCompInstance == null) {
2530 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2531 resource.getUniqueId());
2532 BeEcompErrorManager.getInstance().logInternalDataError(
2533 COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2534 resource.getUniqueId(), ErrorSeverity.ERROR);
2535 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2538 String resourceInstanceId = currentCompInstance.getUniqueId();
2540 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2542 if (regMap != null) {
2543 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2545 while (nodesRegValue.hasNext()) {
2546 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2548 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2549 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2550 log.debug("Going to create relation {}", uploadRegInfo.getName());
2551 String regName = uploadRegInfo.getName();
2552 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2553 regCapRelDef.setFromNode(resourceInstanceId);
2554 log.debug("try to find available requirement {} ", regName);
2555 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2556 yamlName, nodesInfoValue, currentCompInstance,
2557 uploadRegInfo.getCapabilityName());
2558 if (eitherReqStatus.isRight()) {
2559 log.debug("failed to find available requirement {} status is {}", regName,
2560 eitherReqStatus.right().value());
2561 return eitherReqStatus.right().value();
2564 RequirementDefinition validReq = eitherReqStatus.left().value();
2565 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2566 .getRelationships();
2567 if (reqAndRelationshipPairList == null) {
2568 reqAndRelationshipPairList = new ArrayList<>();
2570 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2571 reqAndRelationshipPair.setRequirement(regName);
2572 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2573 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2574 RelationshipImpl relationship = new RelationshipImpl();
2575 relationship.setType(validReq.getCapability());
2576 reqAndRelationshipPair.setRelationships(relationship);
2578 ComponentInstance currentCapCompInstance = null;
2579 for (ComponentInstance compInstance : componentInstancesList) {
2580 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2581 currentCapCompInstance = compInstance;
2586 if (currentCapCompInstance == null) {
2587 log.debug("The component instance with name {} not found on resource {} ",
2588 uploadRegInfo.getNode(), resource.getUniqueId());
2589 BeEcompErrorManager.getInstance().logInternalDataError(
2590 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2591 resource.getUniqueId(), ErrorSeverity.ERROR);
2592 return componentsUtils
2593 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2595 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2596 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2597 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2598 currentCapCompInstance, uploadRegInfo);
2599 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2600 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2601 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2602 if (aviableCapForRel == null) {
2603 log.debug("aviable capability was not found. req name is {} component instance is {}",
2604 validReq.getName(), currentCapCompInstance.getUniqueId());
2605 BeEcompErrorManager.getInstance().logInternalDataError(
2606 "aviable capability was not found. req name is " + validReq.getName()
2607 + " component instance is " + currentCapCompInstance.getUniqueId(),
2608 resource.getUniqueId(), ErrorSeverity.ERROR);
2609 return componentsUtils
2610 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2612 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2613 capReqRel.setRelation(reqAndRelationshipPair);
2614 reqAndRelationshipPairList.add(capReqRel);
2615 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2616 relations.add(regCapRelDef);
2619 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
2620 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2622 return componentsUtils.getResponseFormat(ActionStatus.OK);
2625 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2626 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2627 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
2628 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2629 if (MapUtils.isNotEmpty(propMap)) {
2630 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2631 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2633 if (CollectionUtils.isEmpty( originResource.getInputs())) {
2634 log.debug("failed to find properties ");
2635 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2637 originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
2638 for (List<UploadPropInfo> propertyList : propMap.values()) {
2639 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
2641 currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
2642 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2646 private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
2647 UploadPropInfo propertyInfo = propertyList.get(0);
2648 String propName = propertyInfo.getName();
2649 if (!currPropertiesMap.containsKey(propName)) {
2650 log.debug("failed to find property {} ", propName);
2651 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2654 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
2655 ComponentInstanceInput property = null;
2657 String value = null;
2658 List<GetInputValueDataDefinition> getInputs = null;
2659 boolean isValidate = true;
2660 if (propertyInfo.getValue() != null) {
2661 getInputs = propertyInfo.getGet_input();
2662 isValidate = getInputs == null || getInputs.isEmpty();
2664 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2665 curPropertyDef.getType());
2667 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2668 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2671 String innerType = null;
2672 property = new ComponentInstanceInput(curPropertyDef, value, null);
2674 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2676 property.setValue(validPropertyVAlue);
2678 if (isNotEmpty(getInputs)) {
2679 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2680 for (GetInputValueDataDefinition getInput : getInputs) {
2681 List<InputDefinition> inputs = resource.getInputs();
2682 if (CollectionUtils.isEmpty(inputs)) {
2683 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
2684 property, currentCompInstance.getUniqueId());
2685 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2688 Optional<InputDefinition> optional = inputs.stream()
2689 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
2690 if (!optional.isPresent()) {
2691 log.debug("Failed to find input {} ", getInput.getInputName());
2692 // @@TODO error message
2693 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2695 InputDefinition input = optional.get();
2696 getInput.setInputId(input.getUniqueId());
2697 getInputValues.add(getInput);
2699 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2700 processGetInput(getInputValues, inputs, getInputIndex);
2702 property.setGetInputValues(getInputValues);
2704 instPropList.add(property);
2705 // delete overriden property
2706 currPropertiesMap.remove(property.getName());
2709 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
2710 Optional<InputDefinition> optional;
2711 if (getInputIndex != null) {
2712 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
2714 if (!optional.isPresent()) {
2715 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2716 // @@TODO error message
2717 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2719 InputDefinition inputIndex = optional.get();
2720 getInputIndex.setInputId(inputIndex.getUniqueId());
2721 getInputValues.add(getInputIndex);
2725 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
2726 String propName = prop.getName();
2727 if (!currPropertiesMap.containsKey(propName)) {
2728 currPropertiesMap.put(propName, prop);
2732 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2733 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2734 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
2736 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2737 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2739 List<PropertyDefinition> listFromMap = originResource.getProperties();
2740 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
2741 log.debug("failed to find properties ");
2742 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2744 if (listFromMap == null || listFromMap.isEmpty()) {
2745 return componentsUtils.getResponseFormat(ActionStatus.OK);
2747 for (PropertyDefinition prop : listFromMap) {
2748 String propName = prop.getName();
2749 if (!currPropertiesMap.containsKey(propName)) {
2750 currPropertiesMap.put(propName, prop);
2753 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2754 if (propMap != null && propMap.size() > 0) {
2755 for (List<UploadPropInfo> propertyList : propMap.values()) {
2757 UploadPropInfo propertyInfo = propertyList.get(0);
2758 String propName = propertyInfo.getName();
2759 if (!currPropertiesMap.containsKey(propName)) {
2760 log.debug("failed to find property {} ", propName);
2761 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2764 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2765 ComponentInstanceProperty property = null;
2767 String value = null;
2768 List<GetInputValueDataDefinition> getInputs = null;
2769 boolean isValidate = true;
2770 if (propertyInfo.getValue() != null) {
2771 getInputs = propertyInfo.getGet_input();
2772 isValidate = getInputs == null || getInputs.isEmpty();
2774 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2775 curPropertyDef.getType());
2777 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2778 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2781 String innerType = null;
2782 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2784 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2785 property.setValue(validatePropValue);
2787 if (getInputs != null && !getInputs.isEmpty()) {
2788 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2789 for (GetInputValueDataDefinition getInput : getInputs) {
2790 List<InputDefinition> inputs = resource.getInputs();
2791 if (inputs == null || inputs.isEmpty()) {
2792 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2793 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2795 .map(GetInputValueDataDefinition::getInputName)
2796 .collect(toList()).toString());
2798 InputDefinition input = findInputByName(inputs, getInput);
2799 getInput.setInputId(input.getUniqueId());
2800 getInputValues.add(getInput);
2802 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2803 if (getInputIndex != null) {
2804 input = findInputByName(inputs, getInputIndex);
2805 getInputIndex.setInputId(input.getUniqueId());
2806 getInputValues.add(getInputIndex);
2811 property.setGetInputValues(getInputValues);
2813 instPropList.add(property);
2814 // delete overriden property
2815 currPropertiesMap.remove(property.getName());
2818 // add rest of properties
2819 if (!currPropertiesMap.isEmpty()) {
2820 for (PropertyDefinition value : currPropertiesMap.values()) {
2821 instPropList.add(new ComponentInstanceProperty(value));
2824 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2825 return componentsUtils.getResponseFormat(ActionStatus.OK);
2828 // US740820 Relate RIs according to capability name
2829 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
2830 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2831 if (null == uploadReqInfo.getCapabilityName()
2832 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
2836 return findAvailableCapability(validReq, currentCapCompInstance);
2838 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
2841 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
2842 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2843 CapabilityDefinition cap = null;
2844 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
2845 if (!capMap.containsKey(validReq.getCapability())) {
2848 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
2849 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
2850 if (!capByName.isPresent()) {
2853 cap = capByName.get();
2855 if (isBoundedByOccurrences(cap)) {
2856 String leftOccurrences = cap.getLeftOccurrences();
2857 int left = Integer.parseInt(leftOccurrences);
2860 cap.setLeftOccurrences(String.valueOf(left));
2868 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
2869 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
2870 if (capMap.containsKey(validReq.getCapability())) {
2871 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
2873 for (CapabilityDefinition cap : capList) {
2874 if (isBoundedByOccurrences(cap)) {
2875 String leftOccurrences = cap.getLeftOccurrences() != null ?
2876 cap.getLeftOccurrences() : cap.getMaxOccurrences();
2877 int left = Integer.parseInt(leftOccurrences);
2880 cap.setLeftOccurrences(String.valueOf(left));
2891 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
2892 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
2895 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
2896 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2898 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
2899 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
2900 RequirementDefinition validRegDef = null;
2902 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
2903 for (RequirementDefinition reqDef : entry.getValue()) {
2904 if (reqDef.getName().equals(regName)) {
2905 if (reqDef.getMaxOccurrences() != null
2906 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2907 String leftOccurrences = reqDef.getLeftOccurrences();
2908 if (leftOccurrences == null) {
2909 leftOccurrences = reqDef.getMaxOccurrences();
2911 int left = Integer.parseInt(leftOccurrences);
2914 reqDef.setLeftOccurrences(String.valueOf(left));
2915 validRegDef = reqDef;
2921 validRegDef = reqDef;
2927 if (validRegDef != null) {
2932 for (RequirementDefinition reqDef : list) {
2933 if (reqDef.getName().equals(regName)) {
2934 if (reqDef.getMaxOccurrences() != null
2935 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2936 String leftOccurrences = reqDef.getLeftOccurrences();
2937 if (leftOccurrences == null) {
2938 leftOccurrences = reqDef.getMaxOccurrences();
2940 int left = Integer.parseInt(leftOccurrences);
2943 reqDef.setLeftOccurrences(String.valueOf(left));
2944 validRegDef = reqDef;
2950 validRegDef = reqDef;
2956 if (validRegDef == null) {
2957 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2958 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2959 return Either.right(responseFormat);
2961 return Either.left(validRegDef);
2964 private Resource createResourceInstances(String yamlName, Resource resource,
2965 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2966 Map<String, Resource> nodeNamespaceMap) {
2968 Either<Resource, ResponseFormat> eitherResource = null;
2969 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2970 if (isEmpty(uploadResInstancesMap)) {
2971 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2972 throw new ComponentException(responseFormat);
2974 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2975 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2976 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2978 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2979 uploadResInstancesMap
2981 .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2983 if (isNotEmpty(resourcesInstancesMap)) {
2984 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
2985 resourcesInstancesMap, false);
2986 if (status != null && status != StorageOperationStatus.OK) {
2987 log.debug("Failed to add component instances to container component {}", resource.getName());
2988 ResponseFormat responseFormat = componentsUtils
2989 .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
2990 eitherResource = Either.right(responseFormat);
2991 throw new ComponentException(eitherResource.right().value());
2994 log.debug("*************Going to get resource {}", resource.getUniqueId());
2995 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2996 .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
2997 log.debug("*************finished to get resource {}", resource.getUniqueId());
2998 if (eitherGetResource.isRight()) {
2999 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3000 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3001 throw new ComponentException(responseFormat);
3003 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) {
3004 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3005 BeEcompErrorManager.getInstance().logBeDaoSystemError(
3006 "Error when create resource instance from csar. ComponentInstances list empty");
3007 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3009 return eitherGetResource.left().value();
3012 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3013 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
3014 Either<Resource, ResponseFormat> eitherResource;
3015 log.debug("*************Going to create resource instances {}", yamlName);
3016 // updating type if the type is node type name - we need to take the
3018 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3019 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3020 uploadComponentInstanceInfo
3021 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3023 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3024 existingnodeTypeMap);
3026 ComponentInstance componentInstance = new ComponentInstance();
3027 componentInstance.setComponentUid(refResource.getUniqueId());
3028 ComponentTypeEnum containerComponentType = resource.getComponentType();
3029 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3030 if (containerNodeType.equals(NodeTypeEnum.Resource)
3031 && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3032 && isNotEmpty(refResource.getCapabilities())) {
3033 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3034 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3035 refResource.getUniqueId(), refResource.getCapabilities(),
3036 uploadComponentInstanceInfo.getCapabilities());
3037 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3039 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3041 "createResourceInstances - not found lates version for resource instance with name {} and type ",
3042 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3043 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3044 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3045 throw new ComponentException(responseFormat);
3047 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3048 componentInstance.setName(uploadComponentInstanceInfo.getName());
3049 componentInstance.setIcon(origResource.getIcon());
3050 resourcesInstancesMap.put(componentInstance, origResource);
3053 private ComponentParametersView getComponentWithInstancesFilter() {
3054 ComponentParametersView parametersView = new ComponentParametersView();
3055 parametersView.disableAll();
3056 parametersView.setIgnoreComponentInstances(false);
3057 parametersView.setIgnoreInputs(false);
3058 // inputs are read when creating
3059 // property values on instances
3060 parametersView.setIgnoreUsers(false);
3061 return parametersView;
3064 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3065 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3066 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3067 if (originCapabilities.containsKey(currEntry.getKey())) {
3068 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3071 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3072 capabilities.getValue().stream().forEach(cap -> {
3073 if (uploadedCapabilities.containsKey(cap.getName())) {
3074 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3075 c.setName(cap.getName());
3076 c.setType(cap.getType());
3084 private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
3085 Map<String, Resource> nodeNamespaceMap) {
3087 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3088 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3089 Resource refResource;
3090 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3091 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3093 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3094 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3095 if (findResourceEither.isRight()) {
3097 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3098 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3099 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3100 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3101 throw new ComponentException(responseFormat);
3103 refResource = findResourceEither.left().value();
3104 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3106 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3107 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3109 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3110 refResource.getName(), componentState);
3111 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3112 refResource.getComponentType().getValue(), refResource.getName(), componentState);
3113 throw new ComponentException(responseFormat);
3116 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3117 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3118 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3119 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3120 throw new ComponentException(responseFormat);
3126 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
3127 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3128 boolean forceCertificationAllowed) {
3130 Either<Resource, ResponseFormat> result = null;
3132 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3133 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3134 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3135 if (result.isRight()) {
3138 resource = result.left().value();
3140 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3141 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
3142 resource, user, false, inTransaction, needLock);
3143 result = eitherPopulated.isLeft() ? Either.left(resource)
3144 : Either.right(eitherPopulated.right().value());
3147 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3148 } catch (Exception e) {
3149 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3150 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3152 if (result == null || result.isRight()) {
3153 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3154 if (!inTransaction) {
3155 titanDao.rollback();
3157 } else if (!inTransaction) {
3163 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
3164 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3165 return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
3166 lifecycleChangeInfo, inTransaction, needLock);
3169 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
3170 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3171 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3175 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
3176 Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
3177 CsarInfo csarInfo, String nodeName, boolean isNested) {
3179 ImmutablePair<Resource, ActionStatus> result = null;
3180 // check if resource already exists (search by tosca name = type)
3181 boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3182 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3183 .getLatestByToscaResourceName(resource.getToscaResourceName());
3185 if (latestByToscaName.isLeft()) {
3186 Resource foundResource = latestByToscaName.left().value();
3187 // we don't allow updating names of top level types
3188 if (!isNestedResource &&
3189 !StringUtils.equals(resource.getName(), foundResource.getName())) {
3190 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3191 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3192 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3193 foundResource.getName(), resource.getToscaResourceName());
3194 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3195 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3196 throwComponentException(responseFormat);
3198 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3199 } else if (isNotFound(latestByToscaName)) {
3200 if (isNestedResource) {
3201 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
3203 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3206 StorageOperationStatus status = latestByToscaName.right().value();
3207 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3208 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3209 componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
3210 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3211 throwComponentException(responseFormat);
3216 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3217 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3220 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
3221 Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
3222 resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
3223 if (latestByToscaName.isLeft()) {
3224 Resource nestedResource = (Resource) latestByToscaName.left().value();
3225 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3226 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
3227 ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3228 if (eitherValidation.isRight()) {
3229 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3231 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3233 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3237 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3238 return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
3241 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
3242 User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3243 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3244 validateResourceBeforeCreate(resource, user,
3245 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3246 Resource createdResource = createResourceByDao(resource, user,
3247 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
3248 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
3249 ActionStatus.CREATED);
3250 ASDCKpiApi.countImportResourcesKPI();
3251 return resourcePair;
3254 public boolean isResourceExist(String resourceName) {
3255 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3256 return latestByName.isLeft();
3259 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3260 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3262 String lockedResourceId = oldResource.getUniqueId();
3263 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3264 oldResource.getVersion(), oldResource.getLifecycleState());
3265 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3267 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3268 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3269 mergeOldResourceMetadataWithNew(oldResource, newResource);
3271 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3272 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3273 // contact info normalization
3274 newResource.setContactId(newResource.getContactId().toLowerCase());
3275 // non-updatable fields
3276 newResource.setCreatorUserId(user.getUserId());
3277 newResource.setCreatorFullName(user.getFullName());
3278 newResource.setLastUpdaterUserId(user.getUserId());
3279 newResource.setLastUpdaterFullName(user.getFullName());
3280 newResource.setUniqueId(oldResource.getUniqueId());
3281 newResource.setVersion(oldResource.getVersion());
3282 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3283 newResource.setLifecycleState(oldResource.getLifecycleState());
3284 newResource.setUUID(oldResource.getUUID());
3285 newResource.setNormalizedName(oldResource.getNormalizedName());
3286 newResource.setSystemName(oldResource.getSystemName());
3287 if (oldResource.getCsarUUID() != null) {
3288 newResource.setCsarUUID(oldResource.getCsarUUID());
3290 if (oldResource.getImportedToscaChecksum() != null) {
3291 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3293 newResource.setAbstract(oldResource.isAbstract());
3295 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
3296 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3298 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3299 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3301 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3302 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3305 // created without tosca artifacts - add the placeholders
3306 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3307 setToscaArtifactsPlaceHolders(newResource, user);
3310 if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3311 newResource.setInterfaces(oldResource.getInterfaces());
3314 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3315 .overrideComponent(newResource, oldResource);
3317 if (overrideResource.isRight()) {
3318 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3319 componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3320 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3322 throwComponentException(responseFormat);
3325 log.debug("Resource updated successfully!!!");
3326 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3327 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3328 ResourceVersionInfo.newBuilder()
3329 .state(oldResource.getLifecycleState()
3331 .version(oldResource.getVersion())
3334 resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3336 return resourcePair;
3338 if (resourcePair == null) {
3339 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3340 titanDao.rollback();
3341 } else if (!inTransaction) {
3345 log.debug("unlock resource {}", lockedResourceId);
3346 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3353 * Merge old resource with new. Keep old category and vendor name without
3356 * @param oldResource
3357 * @param newResource
3359 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3361 // keep old category and vendor name without change
3362 // merge the rest of the resource metadata
3363 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3364 newResource.setTags(oldResource.getTags());
3367 if (newResource.getDescription() == null) {
3368 newResource.setDescription(oldResource.getDescription());
3371 if (newResource.getVendorRelease() == null) {
3372 newResource.setVendorRelease(oldResource.getVendorRelease());
3375 if (newResource.getResourceVendorModelNumber() == null) {
3376 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3379 if (newResource.getContactId() == null) {
3380 newResource.setContactId(oldResource.getContactId());
3383 newResource.setCategories(oldResource.getCategories());
3384 if (newResource.getVendorName() == null) {
3385 newResource.setVendorName(oldResource.getVendorName());
3389 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3390 boolean inTransaction, boolean needLock) {
3392 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3394 return lifecycleBusinessLogic.changeState(
3395 oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3396 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3398 .on(response -> failOnChangeState(response, user, oldResource, newResource));
3403 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3404 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3405 response.getFormattedMessage());
3406 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3407 ResourceVersionInfo.newBuilder()
3408 .state(oldResource.getLifecycleState().name())
3409 .version(oldResource.getVersion())
3411 throw new ComponentException(response);
3414 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3416 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3417 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3418 validateLifecycleTypesCreate(user, resource, actionEnum);
3419 validateResourceType(user, resource, actionEnum);
3420 resource.setCreatorUserId(user.getUserId());
3421 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3422 resource.setContactId(resource.getContactId().toLowerCase());
3423 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3424 String resourceSystemName;
3425 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3426 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3428 resourceSystemName = resource.getSystemName();
3430 resource.setToscaResourceName(CommonBeUtils
3431 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3434 // Generate invariant UUID - must be here and not in operation since it
3435 // should stay constant during clone
3437 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3438 resource.setInvariantUUID(invariantUUID);
3443 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3444 AuditingActionEnum actionEnum) {
3445 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3446 if (resource.getResourceType() == null) {
3447 log.debug("Invalid resource type for resource");
3448 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3449 eitherResult = Either.right(errorResponse);
3450 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3452 return eitherResult;
3455 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3456 AuditingActionEnum actionEnum) {
3457 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3458 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3459 log.debug("validate interface lifecycle Types Exist");
3460 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3461 while (intItr.hasNext() && eitherResult.isLeft()) {
3462 InterfaceDefinition interfaceDefinition = intItr.next();
3463 String intType = interfaceDefinition.getUniqueId();
3464 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3465 .getInterface(intType);
3466 if (eitherCapTypeFound.isRight()) {
3467 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3468 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3469 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3470 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3471 intType, resource.getName());
3472 BeEcompErrorManager.getInstance()
3473 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3474 log.debug("request to data model failed with error: {}",
3475 eitherCapTypeFound.right().value().name());
3478 ResponseFormat errorResponse = componentsUtils
3479 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3480 eitherResult = Either.right(errorResponse);
3481 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3486 return eitherResult;
3489 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3490 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3491 boolean inTransaction) {
3493 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3494 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3495 log.debug("validate capability Types Exist - capabilities section");
3497 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3499 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3500 eitherResult, typeEntry, inTransaction);
3501 if (eitherResult.isRight()) {
3502 return Either.right(eitherResult.right().value());
3507 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3508 log.debug("validate capability Types Exist - requirements section");
3509 for (String type : resource.getRequirements().keySet()) {
3510 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3511 resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3512 if (eitherResult.isRight()) {
3513 return Either.right(eitherResult.right().value());
3518 return eitherResult;
3521 // @param typeObject- the object to which the validation is done
3522 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3523 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3524 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3525 boolean inTransaction) {
3526 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3527 .getCapabilityType(type, inTransaction);
3528 if (eitherCapTypeFound.isRight()) {
3529 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3530 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3531 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3532 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3533 resource.getName());
3534 BeEcompErrorManager.getInstance()
3535 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3537 log.debug("Trying to get capability type {} failed with error: {}", type,
3538 eitherCapTypeFound.right().value().name());
3539 ResponseFormat errorResponse = null;
3541 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3543 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3546 eitherResult = Either.right(errorResponse);
3547 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3549 return eitherResult;
3552 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3553 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3554 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3555 boolean inTransaction) {
3556 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3557 .getCapabilityType(typeEntry.getKey(), inTransaction);
3558 if (eitherCapTypeFound.isRight()) {
3559 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3560 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3561 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3562 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3563 typeEntry.getKey(), resource.getName());
3564 BeEcompErrorManager.getInstance()
3565 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3567 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3568 eitherCapTypeFound.right().value().name());
3569 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3570 typeEntry.getKey());
3571 eitherResult = Either.right(errorResponse);
3572 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3574 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3575 if (capabilityTypeDefinition.getProperties() != null) {
3576 for (CapabilityDefinition capDef : typeEntry.getValue()) {
3577 List<ComponentInstanceProperty> properties = capDef.getProperties();
3578 if (properties == null || properties.isEmpty()) {
3579 properties = new ArrayList<>();
3580 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3581 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3582 properties.add(newProp);
3585 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3586 PropertyDefinition porpFromDef = prop.getValue();
3587 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3588 for (ComponentInstanceProperty cip : properties) {
3589 if (!cip.getName().equals(porpFromDef.getName())) {
3590 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3591 propsToAdd.add(newProp);
3594 if (!propsToAdd.isEmpty()) {
3595 properties.addAll(propsToAdd);
3599 capDef.setProperties(properties);
3602 return eitherResult;
3605 public Resource createResourceByDao(Resource resource, User user,
3606 AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3609 // lock new resource name in order to avoid creation resource with same
3611 Resource createdResource = null;
3612 if (!inTransaction) {
3613 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3615 if (lockResult.isRight()) {
3616 ResponseFormat responseFormat = lockResult.right().value();
3617 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3618 throw new ComponentException(responseFormat);
3621 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3624 if (resource.deriveFromGeneric()) {
3625 handleResourceGenericType(resource);
3627 createdResource = createResourceTransaction(resource, user, isNormative
3629 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3630 createdResource, actionEnum);
3631 ASDCKpiApi.countCreatedResourcesKPI();
3632 } catch(ComponentException e) {
3633 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
3634 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3636 } catch (StorageException e){
3637 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3638 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3642 if (!inTransaction) {
3643 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3644 NodeTypeEnum.Resource);
3647 return createdResource;
3650 private Resource createResourceTransaction(Resource resource, User user,
3651 boolean isNormative) {
3652 // validate resource name uniqueness
3653 log.debug("validate resource name");
3654 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3655 resource.getName(), resource.getResourceType(), resource.getComponentType());
3656 if (eitherValidation.isRight()) {
3657 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3658 eitherValidation.right().value());
3659 ResponseFormat errorResponse = componentsUtils
3660 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3661 throw new ComponentException(errorResponse);
3663 if (eitherValidation.left().value()) {
3664 log.debug("resource with name: {}, already exists", resource.getName());
3665 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3666 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3667 throw new ComponentException(errorResponse);
3670 log.debug("send resource {} to dao for create", resource.getName());
3672 createArtifactsPlaceHolderData(resource, user);
3675 log.debug("enrich resource with creator, version and state");
3676 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3677 resource.setVersion(INITIAL_VERSION);
3678 resource.setHighestVersion(true);
3679 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3680 resource.setAbstract(false);
3683 return toscaOperationFacade.createToscaComponent(resource)
3685 .on(r->throwComponentExceptionByResource(r, resource));
3688 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3689 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3690 componentsUtils.convertFromStorageResponse(status), resource);
3691 throw new ComponentException(responseFormat);
3694 private void createArtifactsPlaceHolderData(Resource resource, User user) {
3695 // create mandatory artifacts
3697 // TODO it must be removed after that artifact uniqueId creation will be
3698 // moved to ArtifactOperation
3700 setInformationalArtifactsPlaceHolder(resource, user);
3701 setDeploymentArtifactsPlaceHolder(resource, user);
3702 setToscaArtifactsPlaceHolders(resource, user);
3705 @SuppressWarnings("unchecked")
3707 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3708 Resource resource = (Resource) component;
3709 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3710 if (artifactMap == null) {
3711 artifactMap = new HashMap<>();
3713 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3714 .getConfiguration().getDeploymentResourceArtifacts();
3715 if (deploymentResourceArtifacts != null) {
3716 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3717 deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3719 resource.setDeploymentArtifacts(artifactMap);
3722 private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3723 boolean shouldCreateArtifact = true;
3724 Map<String, Object> artifactDetails = (Map<String, Object>) v;
3725 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3726 if (object != null) {
3727 List<String> artifactTypes = (List<String>) object;
3728 if (!artifactTypes.contains(resource.getResourceType().name())) {
3729 shouldCreateArtifact = false;
3733 log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3736 if (shouldCreateArtifact) {
3737 if (artifactsBusinessLogic != null) {
3738 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3739 resource.getUniqueId(), k, (Map<String, Object>) v,
3740 user, ArtifactGroupTypeEnum.DEPLOYMENT);
3741 if (artifactDefinition != null
3742 && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3743 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3749 @SuppressWarnings("unchecked")
3750 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3751 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3752 if (artifactMap == null) {
3753 artifactMap = new HashMap<>();
3755 String resourceUniqueId = resource.getUniqueId();
3756 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3757 .getExcludeResourceCategory();
3758 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3759 .getExcludeResourceType();
3760 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3761 .getConfiguration().getInformationalResourceArtifacts();
3762 List<CategoryDefinition> categories = resource.getCategories();
3763 boolean isCreateArtifact = true;
3764 if (exludeResourceCategory != null) {
3765 String category = categories.get(0).getName();
3766 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3768 if (isCreateArtifact && exludeResourceType != null) {
3769 String resourceType = resource.getResourceType().name();
3770 isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3772 if (informationalResourceArtifacts != null && isCreateArtifact) {
3773 Set<String> keys = informationalResourceArtifacts.keySet();
3774 for (String informationalResourceArtifactName : keys) {
3775 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3776 .get(informationalResourceArtifactName);
3777 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3778 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3779 ArtifactGroupTypeEnum.INFORMATIONAL);
3780 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3784 resource.setArtifacts(artifactMap);
3794 public ResponseFormat deleteResource(String resourceId, User user) {
3795 ResponseFormat responseFormat;
3796 validateUserExists(user, DELETE_RESOURCE, false);
3798 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3799 if (resourceStatus.isRight()) {
3800 log.debug("failed to get resource {}", resourceId);
3801 return componentsUtils
3802 .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3805 Resource resource = resourceStatus.left().value();
3807 StorageOperationStatus result = StorageOperationStatus.OK;
3808 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3809 if (lockResult.isRight()) {
3810 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3815 result = markComponentToDelete(resource);
3816 if (result.equals(StorageOperationStatus.OK)) {
3817 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3819 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3820 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3822 return responseFormat;
3825 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3826 titanDao.rollback();
3830 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3835 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3836 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3837 validateUserExists(user, DELETE_RESOURCE, false);
3838 Resource resource = null;
3839 StorageOperationStatus result = StorageOperationStatus.OK;
3842 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3843 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3844 if (resourceStatus.isRight()) {
3845 log.debug("failed to get resource {} version {}", resourceName, version);
3846 return componentsUtils.getResponseFormatByResource(
3847 componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3850 resource = resourceStatus.left().value();
3853 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3854 titanDao.rollback();
3855 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3856 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3861 if (resource != null) {
3862 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3864 if (lockResult.isRight()) {
3865 result = StorageOperationStatus.GENERAL_ERROR;
3866 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3869 result = markComponentToDelete(resource);
3870 if (!result.equals(StorageOperationStatus.OK)) {
3871 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3872 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3873 return responseFormat;
3877 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3878 titanDao.rollback();
3882 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3885 return responseFormat;
3888 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3891 validateUserExists(user, CREATE_RESOURCE, false);
3894 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3895 if (storageStatus.isRight()) {
3896 log.debug("failed to get resource by id {}", resourceId);
3897 return Either.right(componentsUtils.getResponseFormatByResource(
3898 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3900 if (!(storageStatus.left().value() instanceof Resource)) {
3901 return Either.right(componentsUtils.getResponseFormatByResource(
3902 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
3904 return Either.left(storageStatus.left().value());
3908 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
3911 validateUserExists(userId, "get Resource By Name And Version", false);
3913 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
3914 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
3915 if (getResource.isRight()) {
3916 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
3917 return Either.right(componentsUtils.getResponseFormatByResource(
3918 componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
3920 return Either.left(getResource.left().value());
3924 * updateResourceMetadata
3926 * @param user - modifier data (userId)
3927 * @param inTransaction TODO
3928 * @param resourceIdToUpdate - the resource identifier
3929 * @param newResource
3930 * @return Either<Resource , responseFormat>
3932 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
3933 Resource currentResource, User user, boolean inTransaction) {
3935 validateUserExists(user.getUserId(), "update Resource Metadata", false);
3937 log.debug("Get resource with id {}", resourceIdToUpdate);
3938 boolean needToUnlock = false;
3939 boolean rollbackNeeded = true;
3942 if (currentResource == null) {
3943 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
3944 .getToscaElement(resourceIdToUpdate);
3945 if (storageStatus.isRight()) {
3946 throw new ComponentException(componentsUtils.getResponseFormatByResource(
3947 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
3950 currentResource = storageStatus.left().value();
3952 // verify that resource is checked-out and the user is the last
3954 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
3955 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3959 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
3960 NodeTypeEnum.Resource);
3961 if (!lockResult.equals(StorageOperationStatus.OK)) {
3962 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
3963 NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
3964 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
3965 ResponseFormat responseFormat = componentsUtils
3966 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
3967 throw new ComponentException(responseFormat);
3970 needToUnlock = true;
3972 // critical section starts here
3973 // convert json to object
3975 // Update and updated resource must have a non-empty "derivedFrom"
3977 // This code is not called from import resources, because of root
3978 // VF "derivedFrom" should be null (or ignored)
3979 if (ModelConverter.isAtomicComponent(currentResource)) {
3980 validateDerivedFromNotEmpty(null, newResource, null);
3981 validateDerivedFromNotEmpty(null, currentResource, null);
3983 newResource.setDerivedFrom(null);
3986 Either<Boolean, ResponseFormat> validateAndUpdateInterfacesEither =
3987 interfaceOperationBusinessLogic.validateComponentNameAndUpdateInterfaces(currentResource, newResource);
3988 if (validateAndUpdateInterfacesEither.isRight()) {
3989 log.error("failed to validate and update Interfaces");
3990 rollbackNeeded = true;
3991 throw new ComponentException(validateAndUpdateInterfacesEither.right().value());
3994 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
3995 user, currentResource, false, true);
3996 if (dataModelResponse.isRight()) {
3997 log.debug("failed to update resource metadata!!!");
3998 rollbackNeeded = true;
3999 throw new ComponentException(dataModelResponse.right().value());
4002 log.debug("Resource metadata updated successfully!!!");
4003 rollbackNeeded = false;
4004 return dataModelResponse.left().value();
4006 } catch (ComponentException|StorageException e){
4007 rollback(inTransaction, newResource, null, null);
4011 if (!inTransaction) {
4015 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4020 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4021 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4022 updateVfModuleGroupsNames(currentResource, newResource);
4023 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4024 // Setting last updater and uniqueId
4025 newResource.setContactId(newResource.getContactId().toLowerCase());
4026 newResource.setLastUpdaterUserId(user.getUserId());
4027 newResource.setUniqueId(resourceIdToUpdate);
4028 // Cannot set highest version through UI
4029 newResource.setHighestVersion(currentResource.isHighestVersion());
4030 newResource.setCreationDate(currentResource.getCreationDate());
4032 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4033 newResource, user.getUserId(), inTransaction);
4035 if (processUpdateOfDerivedFrom.isRight()) {
4036 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4037 return Either.right(processUpdateOfDerivedFrom.right().value());
4040 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4041 if (isNotEmpty(newResource.getGroups())) {
4042 for (GroupDefinition group : newResource.getGroups()) {
4043 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4044 groupBusinessLogic.validateAndUpdateGroupMetadata(
4045 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4046 user, newResource.getComponentType(), group, true, false);
4050 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4051 .updateToscaElement(newResource);
4053 if (dataModelResponse.isRight()) {
4054 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4055 componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4056 return Either.right(responseFormat);
4057 } else if (dataModelResponse.left().value() == null) {
4058 log.debug("No response from updateResource");
4059 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4061 return Either.left(dataModelResponse.left().value());
4065 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4066 if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4067 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4069 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4071 newResource.setGroups(updatedGroups);
4075 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4076 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4077 if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4078 String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4079 String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4080 updatedGroup.setName(newGroupName);
4082 return updatedGroup;
4085 * validateResourceFieldsBeforeCreate
4087 * @param user - modifier data (userId)
4088 * @return Either<Boolean , ErrorResponse>
4090 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4091 AuditingActionEnum actionEnum, boolean inTransaction) {
4092 validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4093 // validate category
4094 log.debug("validate category");
4095 validateCategory(user, resource, actionEnum, inTransaction);
4096 // validate vendor name & release & model number
4097 log.debug("validate vendor name");
4098 validateVendorName(user, resource, actionEnum);
4099 log.debug("validate vendor release");
4100 validateVendorReleaseName(user, resource, actionEnum);
4101 log.debug("validate resource vendor model number");
4102 validateResourceVendorModelNumber(user, resource, actionEnum);
4104 log.debug("validate cost");
4105 validateCost(resource);
4106 // validate licenseType
4107 log.debug("validate licenseType");
4108 validateLicenseType(user, resource, actionEnum);
4109 // validate template (derived from)
4110 log.debug("validate derived from");
4111 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4112 resource.setDerivedFrom(null);
4114 validateDerivedFromExist(user, resource, actionEnum);
4115 // warn about non-updatable fields
4116 checkComponentFieldsForOverrideAttempt(resource);
4117 String currentCreatorFullName = resource.getCreatorFullName();
4118 if (currentCreatorFullName != null) {
4119 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4122 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4123 if (currentLastUpdaterFullName != null) {
4124 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4127 Long currentLastUpdateDate = resource.getLastUpdateDate();
4128 if (currentLastUpdateDate != null) {
4129 log.debug("Resource last update date is automatically set and cannot be updated");
4132 Boolean currentAbstract = resource.isAbstract();
4133 if (currentAbstract != null) {
4134 log.debug("Resource abstract is automatically set and cannot be updated");
4137 return Either.left(true);
4141 * validateResourceFieldsBeforeUpdate
4143 * @param currentResource - Resource object to validate
4146 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4147 boolean inTransaction, boolean isNested) {
4148 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4149 warnNonEditableFields(currentResource, updateInfoResource);
4152 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4153 String currentResourceVersion = currentResource.getVersion();
4154 String updatedResourceVersion = updateInfoResource.getVersion();
4156 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4157 log.debug("Resource version is automatically set and cannot be updated");
4160 String currentCreatorUserId = currentResource.getCreatorUserId();
4161 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4163 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4164 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4167 String currentCreatorFullName = currentResource.getCreatorFullName();
4168 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4170 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4171 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4174 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4175 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4177 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4178 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4181 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4182 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4184 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4185 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4188 Long currentCreationDate = currentResource.getCreationDate();
4189 Long updatedCreationDate = updateInfoResource.getCreationDate();
4191 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4192 log.debug("Resource Creation date is automatically set and cannot be updated");
4195 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4196 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4198 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4199 log.debug("Resource last update date is automatically set and cannot be updated");
4202 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4203 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4205 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4206 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4209 Boolean currentAbstract = currentResource.isAbstract();
4210 Boolean updatedAbstract = updateInfoResource.isAbstract();
4212 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4213 log.debug("Resource abstract is automatically set and cannot be updated");
4216 Boolean currentHighestVersion = currentResource.isHighestVersion();
4217 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4219 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4220 log.debug("Resource highest version is automatically set and cannot be updated");
4223 String currentUuid = currentResource.getUUID();
4224 String updatedUuid = updateInfoResource.getUUID();
4226 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4227 log.debug("Resource UUID is automatically set and cannot be updated");
4230 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4231 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4233 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4234 log.debug("Resource Type cannot be updated");
4237 updateInfoResource.setResourceType(currentResource.getResourceType());
4239 String currentInvariantUuid = currentResource.getInvariantUUID();
4240 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4242 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4243 log.debug("Resource invariant UUID is automatically set and cannot be updated");
4244 updateInfoResource.setInvariantUUID(currentInvariantUuid);
4248 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4249 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4250 log.debug("validate resource name before update");
4251 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4252 log.debug("validate description before update");
4253 validateDescriptionAndCleanup(null, updateInfoResource, null);
4254 log.debug("validate icon before update");
4255 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4256 log.debug("validate tags before update");
4257 validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4258 log.debug("validate vendor name before update");
4259 validateVendorName(null, updateInfoResource, null);
4260 log.debug("validate resource vendor model number before update");
4261 validateResourceVendorModelNumber(currentResource, updateInfoResource);
4262 log.debug("validate vendor release before update");
4263 validateVendorReleaseName(null, updateInfoResource, null);
4264 log.debug("validate contact info before update");
4265 validateContactId(null, updateInfoResource, null);
4266 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4267 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4268 log.debug("validate category before update");
4269 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4273 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4274 String resourceNameUpdated = updateInfoResource.getName();
4275 String resourceNameCurrent = currentResource.getName();
4276 if (resourceNameCurrent.equals(resourceNameUpdated)) {
4279 // In case of CVFC type we should support the case of old VF with CVFC
4280 // instances that were created without the "Cvfc" suffix
4281 return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4282 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4285 private String addCvfcSuffixToResourceName(String resourceName) {
4286 return resourceName + "Cvfc";
4289 private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4290 boolean hasBeenCertified, boolean isNested) {
4291 String resourceNameUpdated = updateInfoResource.getName();
4292 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4293 if (isNested || !hasBeenCertified) {
4294 validateComponentName(null, updateInfoResource, null);
4295 validateResourceNameUniqueness(updateInfoResource);
4296 currentResource.setName(resourceNameUpdated);
4297 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4298 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4301 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4302 resourceNameUpdated);
4303 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4308 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4309 String iconUpdated = updateInfoResource.getIcon();
4310 String iconCurrent = currentResource.getIcon();
4311 if (!iconCurrent.equals(iconUpdated)) {
4312 if (!hasBeenCertified) {
4313 validateIcon(null, updateInfoResource, null);
4315 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4316 throw new ComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4321 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4322 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4323 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4324 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4325 validateResourceVendorModelNumber(null, updateInfoResource, null);
4329 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4330 boolean hasBeenCertified, boolean inTransaction) {
4331 validateCategory(null, updateInfoResource, null, inTransaction);
4332 if (hasBeenCertified) {
4333 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4334 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4335 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4336 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4337 if (!currentCategory.getName().equals(updateCategory.getName())
4338 || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4339 log.info("Category {} cannot be updated once the resource has been certified once.",
4340 currentResource.getCategories());
4341 ResponseFormat errorResponse = componentsUtils
4342 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4343 return Either.right(errorResponse);
4346 return Either.left(true);
4349 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4350 Resource updateInfoResource, boolean hasBeenCertified) {
4352 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4353 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4354 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4355 || updatedDerivedFrom.isEmpty()) {
4356 log.trace("Update normative types");
4357 return Either.left(true);
4360 String derivedFromCurrent = currentDerivedFrom.get(0);
4361 String derivedFromUpdated = updatedDerivedFrom.get(0);
4363 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4364 if (!hasBeenCertified) {
4365 validateDerivedFromExist(null, updateInfoResource, null);
4367 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4368 currentResource, updateInfoResource, null);
4370 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4371 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4372 return validateDerivedFromExtending;
4376 // For derived from, we must know whether it was actually changed,
4377 // otherwise we must do no action.
4378 // Due to changes it inflicts on data model (remove artifacts,
4379 // properties...), it's not like a flat field which can be
4380 // overwritten if not changed.
4381 // So we must indicate that derived from is not changed
4382 updateInfoResource.setDerivedFrom(null);
4384 return Either.left(true);
4387 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4388 Resource updateInfoResource, boolean hasBeenCertified) {
4390 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4391 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4392 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4393 || updatedDerivedFrom.isEmpty()) {
4394 log.trace("Update normative types");
4395 return Either.left(true);
4398 String derivedFromCurrent = currentDerivedFrom.get(0);
4399 String derivedFromUpdated = updatedDerivedFrom.get(0);
4401 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4402 if (!hasBeenCertified) {
4403 validateDerivedFromExist(null, updateInfoResource, null);
4405 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4406 currentResource, updateInfoResource, null);
4408 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4409 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4410 return validateDerivedFromExtending;
4414 return Either.left(true);
4417 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
4418 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4421 String templateName = resource.getDerivedFrom().get(0);
4422 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4423 .validateToscaResourceNameExists(templateName);
4424 if (dataModelResponse.isRight()) {
4425 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4426 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4427 log.debug("request to data model failed with error: {}", storageStatus);
4428 ResponseFormat responseFormat = componentsUtils
4429 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4430 log.trace("audit before sending response");
4431 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4432 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4433 } else if (!dataModelResponse.left().value()) {
4434 log.info("resource template with name: {}, does not exists", templateName);
4435 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4436 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4437 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4441 // Tal G for extending inheritance US815447
4442 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4443 Resource updateInfoResource, AuditingActionEnum actionEnum) {
4444 String currentTemplateName = currentResource.getDerivedFrom().get(0);
4445 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4447 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4448 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4449 if (dataModelResponse.isRight()) {
4450 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4451 BeEcompErrorManager.getInstance()
4452 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4453 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4454 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4455 log.trace("audit before sending response");
4456 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4457 return Either.right(responseFormat);
4460 if (!dataModelResponse.left().value()) {
4461 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4462 currentTemplateName);
4463 ResponseFormat responseFormat = componentsUtils
4464 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4465 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4467 return Either.right(responseFormat);
4470 return Either.left(true);
4473 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4474 log.debug("validate resource derivedFrom field");
4475 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4476 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4477 log.info("derived from (template) field is missing for the resource");
4478 ResponseFormat responseFormat = componentsUtils
4479 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4480 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4482 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4486 private void validateResourceNameUniqueness(Resource resource) {
4488 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4489 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4490 resource.getComponentType());
4491 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4492 log.debug("resource with name: {}, already exists", resource.getName());
4493 throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4494 resource.getName());
4495 } else if(resourceOperationResponse.isRight()){
4496 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4497 throw new StorageException(resourceOperationResponse.right().value());
4502 private void validateCategory(User user, Resource resource,
4503 AuditingActionEnum actionEnum, boolean inTransaction) {
4505 List<CategoryDefinition> categories = resource.getCategories();
4506 if (CollectionUtils.isEmpty(categories)) {
4507 log.debug(CATEGORY_IS_EMPTY);
4508 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4509 ComponentTypeEnum.RESOURCE.getValue());
4510 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4511 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4512 ComponentTypeEnum.RESOURCE.getValue());
4514 if (categories.size() > 1) {
4515 log.debug("Must be only one category for resource");
4516 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4518 CategoryDefinition category = categories.get(0);
4519 List<SubCategoryDefinition> subcategories = category.getSubcategories();
4520 if (CollectionUtils.isEmpty(subcategories)) {
4521 log.debug("Missinig subcategory for resource");
4522 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4524 if (subcategories.size() > 1) {
4525 log.debug("Must be only one sub category for resource");
4526 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4529 SubCategoryDefinition subcategory = subcategories.get(0);
4531 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4532 log.debug(CATEGORY_IS_EMPTY);
4533 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4534 ComponentTypeEnum.RESOURCE.getValue());
4535 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4536 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4537 ComponentTypeEnum.RESOURCE.getValue());
4539 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4540 log.debug(CATEGORY_IS_EMPTY);
4541 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4542 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4543 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4544 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4547 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4550 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4551 User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4552 ResponseFormat responseFormat;
4553 if (category != null && subcategory != null) {
4554 log.debug("validating resource category {} against valid categories list", category);
4555 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4556 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4557 if (categories.isRight()) {
4558 log.debug("failed to retrive resource categories from Titan");
4559 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4560 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4561 throw new ComponentException(categories.right().value());
4563 List<CategoryDefinition> categoryList = categories.left().value();
4564 Optional<CategoryDefinition> foundCategory = categoryList.stream()
4565 .filter(cat -> cat.getName().equals(category.getName()))
4567 if(!foundCategory.isPresent()){
4568 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4569 category, categoryList);
4570 failOnInvalidCategory(user, resource, actionEnum);
4572 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4575 .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4577 if(!foundSubcategory.isPresent()){
4578 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4579 subcategory, foundCategory.get().getSubcategories());
4580 failOnInvalidCategory(user, resource, actionEnum);
4585 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4586 ResponseFormat responseFormat;
4587 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4588 ComponentTypeEnum.RESOURCE.getValue());
4589 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4590 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4591 ComponentTypeEnum.RESOURCE.getValue());
4594 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4595 String vendorRelease = resource.getVendorRelease();
4596 log.debug("validate vendor relese name");
4597 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4598 log.info("vendor relese name is missing.");
4599 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4600 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4601 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4604 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4607 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4608 if (vendorRelease != null) {
4609 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4610 log.info("vendor release exceds limit.");
4611 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4612 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4613 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4614 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4617 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4618 log.info("vendor release is not valid.");
4619 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4620 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4621 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4626 private void validateVendorName(User user, Resource resource,
4627 AuditingActionEnum actionEnum) {
4628 String vendorName = resource.getVendorName();
4629 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4630 log.info("vendor name is missing.");
4631 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4632 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4633 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
4635 validateVendorName(vendorName, user, resource, actionEnum);
4638 private void validateVendorName(String vendorName, User user, Resource resource,
4639 AuditingActionEnum actionEnum) {
4640 if (vendorName != null) {
4641 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4642 log.info("vendor name exceds limit.");
4643 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4644 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4645 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4646 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4647 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4650 if (!ValidationUtils.validateVendorName(vendorName)) {
4651 log.info("vendor name is not valid.");
4652 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4653 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4654 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
4659 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4660 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4661 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4662 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4663 log.info("resource vendor model number exceeds limit.");
4664 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4665 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4666 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4667 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4668 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4669 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4671 // resource vendor model number is currently validated as vendor
4673 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4674 log.info("resource vendor model number is not valid.");
4675 ResponseFormat errorResponse = componentsUtils
4676 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4677 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4678 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4684 private void validateCost(Resource resource) {
4685 String cost = resource.getCost();
4687 if (!ValidationUtils.validateCost(cost)) {
4688 log.debug("resource cost is invalid.");
4689 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4694 private void validateLicenseType(User user, Resource resource,
4695 AuditingActionEnum actionEnum) {
4696 log.debug("validate licenseType");
4697 String licenseType = resource.getLicenseType();
4698 if (licenseType != null) {
4699 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4701 if (!licenseTypes.contains(licenseType)) {
4702 log.debug("License type {} isn't configured", licenseType);
4703 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4704 if (actionEnum != null) {
4705 // In update case, no audit is required
4706 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4708 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4713 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4714 Resource updatedResource, String userId, boolean inTransaction) {
4715 Either<Operation, ResponseFormat> deleteArtifactByInterface;
4716 if (updatedResource.getDerivedFrom() != null) {
4717 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4718 log.debug("1. Removing interface artifacts from graph");
4719 // Remove all interface artifacts of resource
4720 String resourceId = updatedResource.getUniqueId();
4721 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4723 if (interfaces != null) {
4724 Collection<InterfaceDefinition> values = interfaces.values();
4725 for (InterfaceDefinition interfaceDefinition : values) {
4726 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4728 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4729 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4730 if (operations != null) {
4731 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4732 Operation operation = operationEntry.getValue();
4733 ArtifactDefinition implementation = operation.getImplementationArtifact();
4734 if (implementation != null) {
4735 String uniqueId = implementation.getUniqueId();
4736 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4737 uniqueId, operationEntry.getKey(), interfaceType);
4738 // only thing that transacts and locks here
4739 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4742 if (deleteArtifactByInterface.isRight()) {
4743 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4744 if (!inTransaction) {
4745 titanDao.rollback();
4747 return Either.right(deleteArtifactByInterface.right().value());
4750 log.trace("No implementation found for operation {} - nothing to delete",
4751 operationEntry.getKey());
4755 log.trace("No operations found for interface type {}", interfaceType);
4759 log.debug("2. Removing properties");
4760 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4761 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4763 if (findPropertiesOfNode.isRight()
4764 && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4765 log.debug("Failed to remove all properties of resource");
4766 if (!inTransaction) {
4767 titanDao.rollback();
4769 return Either.right(componentsUtils.getResponseFormat(
4770 componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4774 log.debug("Derived from wasn't changed during update");
4777 if (inTransaction) {
4778 return Either.left(true);
4781 return Either.left(true);
4785 /**** Auditing *******************/
4787 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4788 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4789 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4791 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4793 return webApplicationContext.getBean(class1);
4796 public ICapabilityTypeOperation getCapabilityTypeOperation() {
4797 return capabilityTypeOperation;
4800 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4801 this.capabilityTypeOperation = capabilityTypeOperation;
4804 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4805 log.debug("validate resource properties default values");
4806 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4807 List<PropertyDefinition> properties = resource.getProperties();
4808 if (properties != null) {
4809 eitherResult = iterateOverProperties(properties);
4811 return eitherResult;
4814 public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4815 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4817 String innerType = null;
4818 for (PropertyDefinition property : properties) {
4819 if (!propertyOperation.isPropertyTypeValid(property)) {
4820 log.info("Invalid type for property {}", property);
4821 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4822 ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4823 eitherResult = Either.right(responseFormat);
4827 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4828 applicationDataTypeCache);
4829 if (allDataTypes.isRight()) {
4830 return Either.right(allDataTypes.right().value());
4833 type = property.getType();
4835 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4836 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4837 if(responseFormat != null) {
4841 eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4843 return eitherResult;
4846 private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4847 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4848 log.info("Invalid default value for property {}", property);
4849 ResponseFormat responseFormat;
4850 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4851 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4852 property.getName(), type, innerType, property.getDefaultValue());
4854 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4855 property.getName(), type, property.getDefaultValue());
4857 return Either.right(responseFormat);
4860 return Either.left(true);
4863 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4864 ResponseFormat responseFormat = null;
4865 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4866 .isPropertyInnerTypeValid(property, allDataTypes);
4867 innerType = propertyInnerTypeValid.getLeft();
4868 if (!propertyInnerTypeValid.getRight().booleanValue()) {
4869 log.info("Invalid inner type for property {}", property);
4870 responseFormat = componentsUtils.getResponseFormat(
4871 ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4873 return responseFormat;
4877 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4878 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4882 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4883 return componentInstanceBusinessLogic;
4886 private String getComponentTypeForResponse(Component component) {
4887 String componentTypeForResponse = "SERVICE";
4888 if (component instanceof Resource) {
4889 componentTypeForResponse = ((Resource) component).getResourceType().name();
4891 return componentTypeForResponse;
4894 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4897 validateUserExists(user, "Get resource from csar UUID",
4900 // get resource from csar uuid
4901 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4902 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4903 if (either.isRight()) {
4904 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4906 return Either.right(resp);
4909 return Either.left(either.left().value());
4913 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
4914 String componentId, String userId) {
4918 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
4919 String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
4920 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4922 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
4923 uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
4924 return validCapabilitiesMap;
4927 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
4928 String capabilityType = capabilities.get(0).getType();
4929 if (defaultCapabilities.containsKey(capabilityType)) {
4930 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
4931 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
4932 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
4933 validCapabilityList.add(defaultCapability);
4934 validCapabilitiesMap.put(key, validCapabilityList);
4936 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
4940 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
4941 if (CollectionUtils.isEmpty(defaultCapability.getProperties())
4942 && isNotEmpty(capabilities.get(0).getProperties())) {
4943 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
4944 defaultCapability.getName(), resourceId);
4946 "Failed to update capability property values. Property list of fetched capability {} is empty. ",
4947 defaultCapability.getName());
4948 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
4949 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
4950 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
4954 private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
4955 CapabilityDefinition defaultCapability;
4956 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
4957 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
4959 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
4960 .getToscaFullElement(resourceId);
4961 if (getFullComponentRes.isRight()) {
4962 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
4963 getFullComponentRes.right().value());
4964 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
4967 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
4969 return defaultCapability;
4972 private void validateUniquenessUpdateUploadedComponentInstanceCapability(
4973 CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
4974 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
4975 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
4976 .collect(toMap(PropertyDefinition::getName, Function.identity()));
4977 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
4978 for (UploadPropInfo property : uploadedProperties) {
4979 String propertyName = property.getName().toLowerCase();
4980 String propertyType = property.getType();
4981 ComponentInstanceProperty validProperty;
4982 if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
4983 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
4986 validProperty = new ComponentInstanceProperty();
4987 validProperty.setName(propertyName);
4988 if (property.getValue() != null) {
4989 validProperty.setValue(property.getValue().toString());
4991 validProperty.setDescription(property.getDescription());
4992 validProperty.setPassword(property.isPassword());
4993 validProperties.add(validProperty);
4995 defaultCapability.setProperties(validProperties);
4998 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
4999 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
5002 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5003 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5004 Resource resource, User user) {
5006 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5007 ArtifactOperationEnum.class);
5008 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5009 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5010 .left(nodeTypeArtifactsToHandle);
5012 // add all found Csar artifacts to list to upload
5013 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5014 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5015 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5016 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5017 ArtifactDefinition foundArtifact;
5019 if (!existingArtifactsToHandle.isEmpty()) {
5020 foundArtifact = existingArtifactsToHandle.stream()
5021 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5023 if (foundArtifact != null) {
5024 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5025 .getArtifactType()) {
5026 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5027 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5028 // if current artifact already exists, but has
5029 // different content, add him to the list to
5031 artifactsToUpdate.add(currNewArtifact);
5033 // remove found artifact from the list of existing
5034 // artifacts to handle, because it was already
5036 existingArtifactsToHandle.remove(foundArtifact);
5037 // and remove found artifact from the list to
5038 // upload, because it should either be updated or be
5040 artifactsToUpload.remove(currNewArtifact);
5042 log.debug("Can't upload two artifact with the same name {}.",
5043 currNewArtifact.getArtifactName());
5044 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5045 ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5046 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5047 foundArtifact.getArtifactType());
5048 AuditingActionEnum auditingAction = artifactsBusinessLogic
5049 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5050 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5051 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5052 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5053 resource.getComponentType(), null);
5054 responseWrapper.setInnerElement(responseFormat);
5060 if (responseWrapper.isEmpty()) {
5061 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5062 if (currArtifact.getIsFromCsar()) {
5063 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5065 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5070 if (responseWrapper.isEmpty()) {
5071 if (!artifactsToUpload.isEmpty()) {
5072 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5074 if (!artifactsToUpdate.isEmpty()) {
5075 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5077 if (!artifactsToDelete.isEmpty()) {
5078 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5081 if (!responseWrapper.isEmpty()) {
5082 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5084 } catch (Exception e) {
5085 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5086 responseWrapper.setInnerElement(responseFormat);
5087 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5089 return nodeTypeArtifactsToHandleRes;
5092 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5093 String nodeTypeFullName) {
5095 String actualVfName;
5096 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5097 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5098 actualType = ResourceTypeEnum.VFC.name();
5100 actualVfName = vfResourceName;
5101 actualType = nodeResourceType;
5104 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
5105 String nameWithouNamespacePrefix = nodeTypeFullName
5106 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
5107 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5108 String resourceType = findTypes[0];
5109 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
5111 if (actualName.startsWith(Constants.ABSTRACT)) {
5112 toscaResourceName.append(resourceType.toLowerCase()).append('.')
5113 .append(ValidationUtils.convertToSystemName(actualVfName));
5115 toscaResourceName.append(actualType.toLowerCase()).append('.')
5116 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5118 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5119 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5120 previousToscaResourceName
5121 .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
5125 public ICacheMangerOperation getCacheManagerOperation() {
5126 return cacheManagerOperation;
5129 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
5130 this.cacheManagerOperation = cacheManagerOperation;
5134 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
5136 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5137 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
5140 if (resourceResultEither.isRight()) {
5141 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5142 log.debug("Failed to found resource with id {} ", resourceId);
5143 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5146 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5147 return Either.right(componentsUtils.getResponseFormatByResource(
5148 componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5151 Resource resource = resourceResultEither.left().value();
5152 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5153 dataParamsToReturn);
5154 return Either.left(dataTransfer);
5158 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5159 Resource resource = (Resource) clonedComponent;
5160 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5161 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5162 .shouldUpgradeToLatestDerived(resource);
5163 if (shouldUpgradeToLatestDerived.isRight()) {
5164 return Either.right(
5165 componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5167 return Either.left(shouldUpgradeToLatestDerived.left().value());
5169 return super.shouldUpgradeToLatestDerived(clonedComponent);