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 {} ";
128 private ICapabilityTypeOperation capabilityTypeOperation = null;
131 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
134 private LifecycleBusinessLogic lifecycleBusinessLogic;
137 private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
140 private ResourceImportManager resourceImportManager;
143 private InputsBusinessLogic inputsBusinessLogic;
146 private CompositionBusinessLogic compositionBusinessLogic;
149 private ICacheMangerOperation cacheManagerOperation;
152 private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
155 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
158 private MergeInstanceUtils mergeInstanceUtils;
161 private UiComponentDataConverter uiComponentDataConverter;
164 private CsarBusinessLogic csarBusinessLogic;
167 * Default constructor
169 public ResourceBusinessLogic() {
170 log.debug("ResourceBusinessLogic started");
173 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
174 return lifecycleBusinessLogic;
177 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
178 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
181 public IElementOperation getElementDao() {
185 public void setElementDao(IElementOperation elementDao) {
186 this.elementDao = elementDao;
189 public IUserBusinessLogic getUserAdmin() {
190 return this.userAdmin;
193 public void setUserAdmin(UserBusinessLogic userAdmin) {
194 this.userAdmin = userAdmin;
197 public ComponentsUtils getComponentsUtils() {
198 return this.componentsUtils;
201 public void setComponentsUtils(ComponentsUtils componentsUtils) {
202 this.componentsUtils = componentsUtils;
205 public ArtifactsBusinessLogic getArtifactsManager() {
206 return artifactsBusinessLogic;
209 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
210 this.artifactsBusinessLogic = artifactsManager;
213 public ApplicationDataTypeCache getApplicationDataTypeCache() {
214 return applicationDataTypeCache;
217 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
218 this.applicationDataTypeCache = applicationDataTypeCache;
221 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
222 this.interfaceTypeOperation = interfaceTypeOperation;
226 * the method returns a list of all the resources that are certified, the
227 * returned resources are only abstract or only none abstract according to
234 public List<Resource> getAllCertifiedResources(boolean getAbstract,
235 HighestFilterEnum highestFilter, String userId) {
236 User user = validateUserExists(userId, "get All Certified Resources", false);
237 Boolean isHighest = null;
238 switch (highestFilter) {
244 case NON_HIGHEST_ONLY:
250 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
251 .getAllCertifiedResources(getAbstract, isHighest);
253 if (getResponse.isRight()) {
254 throw new StorageException(getResponse.right().value());
257 return getResponse.left().value();
260 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
261 ResourceTypeEnum resourceTypeEnum, String userId) {
263 validateUserExists(userId, "validate Resource Name Exists", false);
265 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
266 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
270 if (dataModelResponse.isLeft()) {
271 Map<String, Boolean> result = new HashMap<>();
272 result.put("isValid", dataModelResponse.left().value());
273 log.debug("validation was successfully performed.");
274 return Either.left(result);
277 ResponseFormat responseFormat = componentsUtils
278 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
280 return Either.right(responseFormat);
283 public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
284 User user, Map<String, byte[]> csarUIPayload, String payloadName) {
285 validateResourceBeforeCreate(resource, user, false);
286 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
287 if (StringUtils.isNotEmpty(csarUUID)) {
288 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
289 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
290 return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
293 return createResourceByDao(resource, user, auditingAction, false, false);
296 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
297 Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
298 String csarUUID = payloadName;
299 String csarVersion = null;
300 Resource updatedResource = null;
301 if (payloadName == null) {
302 csarUUID = resource.getCsarUUID();
303 csarVersion = resource.getCsarVersion();
305 if (csarUUID != null && !csarUUID.isEmpty()) {
306 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
307 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
308 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
309 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
310 overrideImmutableMetadata(oldResource, resource);
312 validateResourceBeforeCreate(resource, user, false);
313 String oldCsarVersion = oldResource.getCsarVersion();
314 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
316 // (on boarding flow): If the update includes same csarUUID and
317 // same csarVersion as already in the VF - no need to import the
318 // csar (do only metadata changes if there are).
319 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
320 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
323 updatedResource = updateResourceFromCsar(oldResource, resource, user,
324 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
327 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
328 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
330 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
331 throw new ComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
333 return updatedResource;
336 private void validateCsarIsNotAlreadyUsed(Resource oldResource,
337 Resource resource, String csarUUID, User user) {
338 // (on boarding flow): If the update includes a csarUUID: verify this
339 // csarUUID is not in use by another VF, If it is - use same error as
341 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
342 // select another or update the existing VF." %1 - csarUUID, %2 - VF
344 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
345 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
346 if (resourceLinkedToCsarRes.isRight()) {
347 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
348 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
349 resource.getSystemName());
350 throw new StorageException(resourceLinkedToCsarRes.right().value());
352 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
353 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
354 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
355 resourceLinkedToCsarRes.left().value().getName());
356 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
357 throw new ComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
358 resourceLinkedToCsarRes.left().value().getName());
362 private void validateCsarUuidMatching(Resource resource,
363 Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
364 // (on boarding flow): If the update includes csarUUID which is
365 // different from the csarUUID of the VF - fail with
366 // error: "Error: Resource %1 cannot be updated using since it is linked
367 // to a different VSP" %1 - VF name
368 String oldCsarUUID = oldResource.getCsarUUID();
369 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
371 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
372 resourceUniqueId, csarUUID, oldCsarUUID);
373 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
374 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
375 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
376 throw new ComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
380 private Resource getResourceByUniqueId(String resourceUniqueId) {
381 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
382 if (oldResourceRes.isRight()) {
383 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
384 oldResourceRes.right().value());
385 throw new StorageException(oldResourceRes.right().value());
387 return oldResourceRes.left().value();
390 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
391 resource.setName(oldRresource.getName());
392 resource.setIcon(oldRresource.getIcon());
393 resource.setTags(oldRresource.getTags());
394 resource.setCategories(oldRresource.getCategories());
395 resource.setDerivedFrom(oldRresource.getDerivedFrom());
398 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
399 User user, AuditingActionEnum updateResource, boolean inTransaction,
400 Map<String, byte[]> csarUIPayload, String csarUUID) {
401 Resource updatedResource = null;
402 validateLifecycleState(oldResource, user);
403 String lockedResourceId = oldResource.getUniqueId();
404 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
405 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
406 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
407 "update Resource From Csar");
408 if (lockResult.isRight()) {
409 throw new ComponentException(lockResult.right().value());
412 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
414 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
415 nodeTypesInfo, csarInfo, oldResource);
416 if (findNodeTypesArtifactsToHandleRes.isRight()) {
417 log.debug("failed to find node types for update with artifacts during import csar {}. ",
418 csarInfo.getCsarUUID());
419 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
421 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
424 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
425 csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
427 connectUiRelations(oldResource, updatedResource);
429 } catch (ComponentException|StorageException e){
430 rollback(inTransaction, newResource, createdArtifacts, null);
435 log.debug("unlock resource {}", lockedResourceId);
436 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
438 return updatedResource;
442 private void validateLifecycleState(Resource oldResource, User user) {
443 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
444 !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
445 log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
446 oldResource.getLastUpdaterUserId(), user.getUserId());
447 throw new ComponentException(ActionStatus.RESTRICTED_OPERATION);
451 private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
452 Either<Resource, ResponseFormat> result;
454 List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
456 StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
457 if (status == StorageOperationStatus.OK) {
458 newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
459 result = Either.left(newResource);
461 result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
467 private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
468 AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
469 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
470 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
471 String nodeName, boolean isNested) {
472 boolean inTransaction = true;
473 boolean shouldLock = false;
474 Resource preparedResource = null;
475 ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
477 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
478 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
479 preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
480 inTransaction, shouldLock, isNested).left;
481 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
482 handleResourceGenericType(preparedResource);
483 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
484 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
485 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
486 preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
487 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
488 } catch (ComponentException e) {
489 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
490 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
491 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
493 } catch (StorageException e){
494 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
495 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
496 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
499 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
500 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
501 preparedResource.getSystemName());
502 if (validateUpdateVfGroupNamesRes.isRight()) {
504 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
506 // add groups to resource
507 Map<String, GroupDefinition> groups;
509 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
510 groups = validateUpdateVfGroupNamesRes.left().value();
512 groups = uploadComponentInstanceInfoMap.getGroups();
514 handleGroupsProperties(preparedResource, groups);
515 preparedResource = updateGroupsOnResource(preparedResource, groups);
516 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
517 nodeTypesArtifactsToHandle);
519 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
520 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
521 if (updateArtifactsEither.isRight()) {
522 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
523 throw new ComponentException(updateArtifactsEither.right().value());
525 preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
527 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
528 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
529 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
531 throw new ComponentException(responseFormat);
533 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
534 return preparedResource;
537 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
538 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
539 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
541 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
542 Resource resource = preparedResource;
544 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
545 .getNodeTypesArtifactsToHandle();
546 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
547 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
548 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
549 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
550 if (handleNodeTypeArtifactsRes.isRight()) {
551 return Either.right(handleNodeTypeArtifactsRes.right().value());
555 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
556 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
557 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
558 if (createdCsarArtifactsEither.isRight()) {
559 return createdCsarArtifactsEither;
562 resource = createdCsarArtifactsEither.left().value();
564 return Either.left(resource);
567 private Resource handleResourceGenericType(Resource resource) {
568 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
569 if (resource.shouldGenerateInputs()) {
570 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
572 return genericResource;
575 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
576 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
578 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
579 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
580 = Either.left(nodeTypesArtifactsToHandle);
583 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
584 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
585 extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
586 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
587 oldResource.getName(), csarInfo.getCsarUUID());
588 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
589 extractedVfcsArtifacts,
590 namespace, vfcToscaNames));
591 } catch (Exception e) {
592 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
593 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
594 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
596 return nodeTypesArtifactsToHandleRes;
599 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
600 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
602 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
603 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
604 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
605 if (!isEmpty(extractedVfcsArtifacts)) {
606 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
607 if (extractedVfcsArtifacts.containsKey(namespace)) {
608 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
610 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
611 } else if (curNodeType != null) {
612 // delete all artifacts if have not received artifacts from
614 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
615 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
616 // delete all informational artifacts
617 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
618 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
620 // delete all deployment artifacts
621 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
622 if (!artifactsToDelete.isEmpty()) {
623 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
626 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
627 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
631 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
632 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
633 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
634 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
635 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
636 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
637 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
638 return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
640 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
645 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
646 Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
648 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
650 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
651 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
652 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
653 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
654 collectExistingArtifacts(curNodeType));
655 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
656 } catch (Exception e) {
657 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
658 throw new ComponentException(ActionStatus.GENERAL_ERROR);
660 return nodeTypeArtifactsToHandle;
663 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
664 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
665 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
666 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
667 if (!artifactsToUpload.isEmpty()) {
668 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
670 if (!artifactsToUpdate.isEmpty()) {
671 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
673 if (!artifactsToDelete.isEmpty()) {
674 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
677 return nodeTypeArtifactsToHandle;
680 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
681 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
682 Map<String, ArtifactDefinition> existingArtifacts) {
683 if (!existingArtifacts.isEmpty()) {
684 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
685 artifactsToDelete.addAll(existingArtifacts.values());
689 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
690 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
692 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
694 if (foundArtifact.isPresent()) {
695 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
696 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
697 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
698 artifactsToUpload.remove(currNewArtifact);
700 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
701 throw new ComponentException(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
702 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
703 foundArtifact.get().getArtifactType());
708 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
709 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
710 foundArtifact.setPayload(currNewArtifact.getPayloadData());
711 foundArtifact.setPayloadData(
712 Base64.encodeBase64String(currNewArtifact.getPayloadData()));
713 foundArtifact.setArtifactChecksum(GeneralUtility
714 .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
715 artifactsToUpdate.add(foundArtifact);
719 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
720 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
721 if (curNodeType == null) {
722 return existingArtifacts;
724 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
725 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
727 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
729 .putAll(curNodeType.getArtifacts().entrySet()
731 .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
732 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
734 return existingArtifacts;
738 * Changes resource life cycle state to checked out
742 * @param inTransaction
745 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
746 Either<Resource, ResponseFormat> checkoutResourceRes;
748 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
749 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
751 "************* Going to change life cycle state of resource {} to not certified checked out. ",
753 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
754 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
755 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
756 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
757 inTransaction, true);
758 if (checkoutRes.isRight()) {
759 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
760 resource.getComponentType().getNodeType(), resource.getUniqueId(),
761 checkoutRes.right().value().getStatus());
762 checkoutResourceRes = Either.right(checkoutRes.right().value());
764 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
767 checkoutResourceRes = Either.left(resource);
769 } catch (Exception e) {
770 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
771 checkoutResourceRes = Either.right(responseFormat);
772 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
775 return checkoutResourceRes;
779 * Handles Artifacts of NodeType
781 * @param nodeTypeResource
782 * @param nodeTypeArtifactsToHandle
784 * @param inTransaction
787 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
788 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
789 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
790 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
791 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
792 Either<Resource, ResponseFormat> changeStateResponse;
794 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
795 if (changeStateResponse.isRight()) {
796 return Either.right(changeStateResponse.right().value());
798 nodeTypeResource = changeStateResponse.left().value();
800 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
801 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
802 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
804 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
805 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
806 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
807 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
808 nodeTypeResource.getName());
809 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
810 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
811 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
812 ignoreLifecycleState, curOperation),
813 false, inTransaction);
814 if (handleNodeTypeArtifactsRequestRes.isRight()) {
815 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
818 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
819 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
821 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
824 if (handleNodeTypeArtifactsRes == null) {
825 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
827 } catch (Exception e) {
828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
829 handleNodeTypeArtifactsRes = Either.right(responseFormat);
830 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
832 return handleNodeTypeArtifactsRes;
835 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
836 String vfResourceName, CsarInfo csarInfo) {
837 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
839 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
840 if (!nodes.isEmpty()) {
841 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
842 while (nodesNameEntry.hasNext()) {
843 Entry<String, Object> nodeType = nodesNameEntry.next();
844 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
845 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
846 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
849 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
850 vfcToscaNames.put(cvfc.getType(),
851 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
853 return vfcToscaNames;
856 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
857 Map<String, Object> nodes = new HashMap<>();
858 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
859 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
861 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
865 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
866 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
867 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
868 if (eitherNodeTypes.isLeft()) {
869 nodes.putAll(eitherNodeTypes.left().value());
873 public Resource createResourceFromCsar(Resource resource, User user,
874 Map<String, byte[]> csarUIPayload, String csarUUID) {
875 log.trace("************* created successfully from YAML, resource TOSCA ");
877 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
879 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
880 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
881 nodeTypesInfo, csarInfo, resource);
882 if (findNodeTypesArtifactsToHandleRes.isRight()) {
883 log.debug("failed to find node types for update with artifacts during import csar {}. ",
884 csarInfo.getCsarUUID());
885 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
887 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
888 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
890 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
891 vfResource.getToscaResourceName());
895 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
896 log.trace("validating resource before create");
897 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
898 // validate user role
899 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
900 // VF / PNF "derivedFrom" should be null (or ignored)
901 if (ModelConverter.isAtomicComponent(resource)) {
902 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
904 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
908 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
909 // nodeTypesArtifactsToCreate, true, false, null
910 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
911 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
912 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
913 boolean shouldLock, boolean inTransaction, String nodeName) {
915 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
916 Resource createdResource;
918 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
919 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
920 createdResource = createResourceAndRIsFromYaml(yamlName, resource,
921 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
922 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
923 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
924 } catch (ComponentException e) {
925 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
926 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
928 } catch (StorageException e){
929 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
930 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
933 return createdResource;
937 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
938 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
939 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
942 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
943 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
944 if (toscaVersion.isRight()) {
945 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
947 Map<String, Object> mapToConvert = new HashMap<>();
948 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
949 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
950 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
951 return csarInfo.getCreatedNodes();
954 private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
955 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
956 .left().orValue(HashMap::new);
959 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) {
960 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
961 Resource vfcCreated = null;
962 while (nodesNameValueIter.hasNext()) {
963 Entry<String, Object> nodeType = nodesNameValueIter.next();
964 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
965 || nodeTypesArtifactsToHandle.isEmpty() ? null
966 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
968 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
969 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
970 vfcCreated = handleNestedVfc(resource,
971 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
973 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
974 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
975 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
976 log.trace("************* Going to create node {}", nodeType.getKey());
977 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
978 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
980 log.debug("************* Finished to create node {}", nodeType.getKey());
982 vfcCreated = resourceCreated.getLeft();
983 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
984 vfcCreated.getToscaResourceName());
986 if (vfcCreated != null) {
987 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
989 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
993 private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
994 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
997 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
998 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1000 log.debug("************* Going to create node types from yaml {}", yamlName);
1001 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
1002 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1003 log.debug("************* Finished to create node types from yaml {}", yamlName);
1005 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1006 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1007 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1008 csarInfo, nodeName, yamlName);
1013 private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1014 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1015 String nodeName, String yamlName) {
1017 Resource oldComplexVfc = null;
1018 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1019 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1020 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1021 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1022 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1023 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1024 nodeName).getRight());
1026 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1027 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1028 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1029 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1030 } else if (oldComplexVfcRes.isLeft()) {
1031 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1032 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1033 oldComplexVfcRes.left().value(), newComplexVfc,
1034 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1035 if (eitherValidation.isLeft()) {
1036 oldComplexVfc = oldComplexVfcRes.left().value();
1039 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1040 oldComplexVfc, newComplexVfc);
1041 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1042 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1043 CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1044 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1045 Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1047 if (result.isRight()) {
1048 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1050 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1051 csarInfo.removeNodeFromQueue();
1052 return result.left().value();
1055 private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1056 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1057 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1059 Resource handleComplexVfcRes;
1060 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1061 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1062 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1063 .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
1064 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1065 if (oldComplexVfc == null) {
1066 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1067 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1069 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1070 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1071 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1073 return handleComplexVfcRes;
1076 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1077 Map<String, NodeTypeInfo> nodesInfo) {
1079 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1080 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1081 csarInfo.addNodeToQueue(nodeName);
1082 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1083 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1086 private String getNodeTypeActualName(String fullName) {
1087 String nameWithouNamespacePrefix = fullName
1088 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1089 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1090 String resourceType = findTypes[0];
1091 return nameWithouNamespacePrefix.substring(resourceType.length());
1094 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1095 String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1096 Resource resourceVf, boolean needLock,
1097 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1098 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1101 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1103 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1104 resourceMetaData.getResourceType(), csarInfo);
1105 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1106 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1107 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1108 nodeNameValue.getKey(), isNested);
1111 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1112 String nodeResourceType, CsarInfo csarInfo) {
1113 // We need to create a Yaml from each node_types in order to create
1114 // resource from each node type using import normative flow.
1115 DumperOptions options = new DumperOptions();
1116 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1117 Yaml yaml = new Yaml(options);
1119 Map<String, Object> node = new HashMap<>();
1120 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1121 .getLeft(), nodeNameValue.getValue());
1122 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1124 return yaml.dumpAsMap(mapToConvert);
1127 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1128 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1129 return Either.left(true);
1132 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1133 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1134 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1135 String nodeName, boolean isNested) {
1137 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1138 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1139 Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1140 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1141 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1142 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
1143 .left().on(this::failOnCertification);
1146 private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
1147 throw new ComponentException(error);
1150 private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1151 String nodeName, User user) {
1152 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1154 // validate nodetype name prefix
1155 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1156 log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1157 Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1158 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1159 yamlName, resourceMetaData.getName(), nodeName);
1162 String actualName = this.getNodeTypeActualName(nodeName);
1163 String namePrefix = nodeName.replace(actualName, "");
1164 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1166 // if we import from csar, the node_type name can be
1167 // org.openecomp.resource.abstract.node_name - in this case we always
1169 if (resourceType.equals(Constants.ABSTRACT)) {
1170 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1173 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1174 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1175 ResourceTypeEnum.values());
1176 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1177 yamlName, resourceMetaData.getName(), nodeName);
1181 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1183 // Setting type from name
1184 String type = resourceType.toUpperCase();
1185 resourceMetaData.setResourceType(type);
1187 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1188 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1189 resourceMetaData.setContactId(user.getUserId());
1190 resourceMetaData.setVendorName(resourceVf.getVendorName());
1191 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1194 List<String> tags = new ArrayList<>();
1195 tags.add(resourceMetaData.getName());
1196 resourceMetaData.setTags(tags);
1199 CategoryDefinition category = new CategoryDefinition();
1200 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1201 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1202 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1203 category.addSubCategory(subCategory);
1204 List<CategoryDefinition> categories = new ArrayList<>();
1205 categories.add(category);
1206 resourceMetaData.setCategories(categories);
1208 return resourceMetaData;
1211 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1212 Map<String, NodeTypeInfo> nodesInfo) {
1213 Resource cvfc = new Resource();
1214 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1215 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1216 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1217 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1218 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1219 cvfc.setAbstract(true);
1220 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1221 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1222 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1223 cvfc.setContactId(csarInfo.getModifier().getUserId());
1224 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1225 cvfc.setVendorName(resourceVf.getVendorName());
1226 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1227 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1228 cvfc.setToscaResourceName(
1229 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1231 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1233 List<String> tags = new ArrayList<>();
1234 tags.add(cvfc.getName());
1237 CategoryDefinition category = new CategoryDefinition();
1238 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1239 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1240 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1241 category.addSubCategory(subCategory);
1242 List<CategoryDefinition> categories = new ArrayList<>();
1243 categories.add(category);
1244 cvfc.setCategories(categories);
1246 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1247 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1248 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1253 private String buildCvfcName(String resourceVfName, String nodeName) {
1254 String nameWithouNamespacePrefix = nodeName
1255 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1256 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1257 String resourceType = findTypes[0];
1258 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1259 return addCvfcSuffixToResourceName(resourceName);
1262 private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
1263 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1264 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1265 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1266 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1267 boolean shouldLock, boolean inTransaction, String nodeName) {
1269 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1272 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1274 if (lockResult.isRight()) {
1275 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1276 throw new ComponentException(lockResult.right().value());
1278 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1281 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1282 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1283 resource = createResourceTransaction(resource,
1284 csarInfo.getModifier(), isNormative);
1285 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1286 log.trace("************* Going to add inputs from yaml {}", yamlName);
1287 if (resource.shouldGenerateInputs())
1288 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1290 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1291 resource = createInputsOnResource(resource, inputs);
1292 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1294 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1296 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1298 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1299 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1300 nodeTypesArtifactsToCreate, nodeName);
1301 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1302 // validate update vf module group names
1303 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1304 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1305 if (validateUpdateVfGroupNamesRes.isRight()) {
1306 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1307 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
1309 // add groups to resource
1310 Map<String, GroupDefinition> groups;
1311 log.trace("************* Going to add groups from yaml {}", yamlName);
1313 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1314 groups = validateUpdateVfGroupNamesRes.left().value();
1316 groups = parsedToscaYamlInfo.getGroups();
1319 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1321 if (createGroupsOnResource.isRight()) {
1322 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1323 throw new ComponentException(createGroupsOnResource.right().value());
1325 resource = createGroupsOnResource.left().value();
1326 log.trace("************* Finished to add groups from yaml {}", yamlName);
1328 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1330 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1331 nodeTypesArtifactsToCreate);
1333 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1334 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1335 if (createArtifactsEither.isRight()) {
1336 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1337 throw new ComponentException(createArtifactsEither.right().value());
1340 resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
1342 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1343 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1344 ASDCKpiApi.countCreatedResourcesKPI();
1347 } catch(ComponentException|StorageException e) {
1348 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1351 if (!inTransaction) {
1355 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1356 NodeTypeEnum.Resource);
1361 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1362 if(!inTransaction) {
1363 titanDao.rollback();
1365 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1366 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1367 log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
1371 private Resource getResourceWithGroups(String resourceId) {
1373 ComponentParametersView filter = new ComponentParametersView();
1374 filter.setIgnoreGroups(false);
1375 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
1376 if (updatedResource.isRight()) {
1377 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
1379 return updatedResource.left().value();
1382 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1383 Map<String, GroupDefinition> groups) {
1384 if (groups != null && !groups.isEmpty()) {
1385 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
1387 handleGroupsProperties(resource, groups);
1388 fillGroupsFinalFields(groupsAsList);
1389 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1390 groupsAsList, true);
1391 if (createGroups.isRight()) {
1392 return Either.right(createGroups.right().value());
1395 return Either.left(resource);
1397 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1398 .getToscaElement(resource.getUniqueId());
1399 if (updatedResource.isRight()) {
1400 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1401 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1402 return Either.right(responseFormat);
1404 return Either.left(updatedResource.left().value());
1407 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1408 List<InputDefinition> inputs = resource.getInputs();
1409 if (MapUtils.isNotEmpty(groups)) {
1412 .filter(g -> isNotEmpty(g.getProperties()))
1413 .flatMap(g -> g.getProperties().stream())
1414 .forEach(p -> handleGetInputs(p, inputs));
1418 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1419 if (isNotEmpty(property.getGetInputValues())) {
1420 if (inputs == null || inputs.isEmpty()) {
1421 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1422 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1424 .map(GetInputValueDataDefinition::getInputName)
1425 .collect(toList()).toString());
1427 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1428 while (getInputValuesIter.hasNext()) {
1429 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1430 InputDefinition input = findInputByName(inputs, getInput);
1431 getInput.setInputId(input.getUniqueId());
1432 if (getInput.getGetInputIndex() != null) {
1433 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1434 input = findInputByName(inputs, getInputIndex);
1435 getInputIndex.setInputId(input.getUniqueId());
1436 getInputValuesIter.add(getInputIndex);
1442 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1443 Optional<InputDefinition> inputOpt = inputs.stream()
1444 .filter(p -> p.getName().equals(getInput.getInputName()))
1446 if (!inputOpt.isPresent()) {
1447 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1448 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1450 return inputOpt.get();
1453 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1454 groupsAsList.forEach(groupDefinition -> {
1455 groupDefinition.setInvariantName(groupDefinition.getName());
1456 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1460 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1461 if (isEmpty(groups)) {
1464 updateOrCreateGroups(resource, groups);
1466 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1467 .getToscaElement(resource.getUniqueId());
1468 if (updatedResource.isRight()) {
1469 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1470 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1472 return updatedResource.left().value();
1475 private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1476 List<GroupDefinition> groupsFromResource = resource.getGroups();
1477 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1478 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1479 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1480 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1481 if (isNotEmpty(groupsFromResource)) {
1482 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1483 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1485 groupsToCreate.addAll(groupsAsList);
1487 if (isNotEmpty(groupsToCreate)) {
1488 fillGroupsFinalFields(groupsToCreate);
1489 if (isNotEmpty(groupsFromResource)) {
1490 groupBusinessLogic.addGroups(resource,
1491 groupsToCreate, true)
1493 .on(this::throwComponentException);
1495 groupBusinessLogic.createGroups(resource,
1496 groupsToCreate, true)
1498 .on(this::throwComponentException);
1501 if (isNotEmpty(groupsToDelete)) {
1502 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1504 .on(this::throwComponentException);
1506 if (isNotEmpty(groupsToUpdate)) {
1507 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1509 .on(this::throwComponentException);
1513 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1514 for (GroupDefinition group : groupsFromResource) {
1515 Optional<GroupDefinition> op = groupsAsList.stream()
1516 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1517 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1518 groupsToDelete.add(group);
1523 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1524 for (GroupDefinition group : groupsAsList) {
1525 Optional<GroupDefinition> op = groupsFromResource.stream()
1526 .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1527 if (op.isPresent()) {
1528 GroupDefinition groupToUpdate = op.get();
1529 groupToUpdate.setMembers(group.getMembers());
1530 groupToUpdate.setCapabilities(group.getCapabilities());
1531 groupToUpdate.setProperties(group.getProperties());
1532 groupsToUpdate.add(groupToUpdate);
1534 groupsToCreate.add(group);
1539 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1540 List<InputDefinition> resourceProperties = resource.getInputs();
1541 if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1543 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1545 if (createInputs.isRight()) {
1546 throw new ComponentException(createInputs.right().value());
1551 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1552 .getToscaElement(resource.getUniqueId());
1553 if (updatedResource.isRight()) {
1554 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1555 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1557 return updatedResource.left().value();
1560 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1562 List<GroupDefinition> result = new ArrayList<>();
1563 List<ComponentInstance> componentInstances = component.getComponentInstances();
1565 if (groups != null) {
1566 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1567 if (validateCyclicGroupsDependencies.isRight()) {
1568 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1570 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1571 String groupName = entry.getKey();
1572 GroupDefinition groupDefinition = entry.getValue();
1573 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1574 updatedGroupDefinition.setMembers(null);
1575 Map<String, String> members = groupDefinition.getMembers();
1576 if (members != null) {
1577 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1579 result.add(updatedGroupDefinition);
1585 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1586 Set<String> compInstancesNames = members.keySet();
1588 if (CollectionUtils.isEmpty(componentInstances)) {
1589 String membersAstString = compInstancesNames.stream().collect(joining(","));
1590 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1591 membersAstString, groupName, component.getNormalizedName());
1592 throw new ComponentException(componentsUtils.getResponseFormat(
1593 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1594 component.getNormalizedName(), getComponentTypeForResponse(component)));
1596 // Find all component instances with the member names
1597 Map<String, String> memberNames = componentInstances.stream()
1598 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1599 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1600 Map<String, String> relevantInstances = memberNames.entrySet().stream()
1601 .filter(n -> compInstancesNames.contains(n.getKey()))
1602 .collect(toMap(Entry::getKey, Entry::getValue));
1604 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1606 List<String> foundMembers = new ArrayList<>();
1607 if (relevantInstances != null) {
1608 foundMembers = relevantInstances.keySet().stream().collect(toList());
1610 compInstancesNames.removeAll(foundMembers);
1611 String membersAstString = compInstancesNames.stream().collect(joining(","));
1612 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1613 groupName, component.getNormalizedName());
1614 throw new ComponentException(componentsUtils.getResponseFormat(
1615 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1616 component.getNormalizedName(), getComponentTypeForResponse(component)));
1618 updatedGroupDefinition.setMembers(relevantInstances);
1622 * This Method validates that there is no cyclic group dependencies. meaning
1623 * group A as member in group B which is member in group A
1628 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1630 Either<Boolean, ResponseFormat> result = Either.left(true);
1632 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1633 while (allGroupsItr.hasNext() && result.isLeft()) {
1634 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1635 // Fetches a group member A
1636 String groupAName = groupAEntry.getKey();
1637 // Finds all group members in group A
1638 Set<String> allGroupAMembersNames = new HashSet<>();
1639 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1640 // If A is a group member of itself found cyclic dependency
1641 if (allGroupAMembersNames.contains(groupAName)) {
1642 ResponseFormat responseFormat = componentsUtils
1643 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1644 result = Either.right(responseFormat);
1647 } catch (Exception e) {
1648 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1649 result = Either.right(responseFormat);
1650 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1656 * This Method fills recursively the set groupMembers with all the members
1657 * of the given group which are also of type group.
1661 * @param allGroupMembers
1664 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1665 Set<String> allGroupMembers) {
1667 // Found Cyclic dependency
1668 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1671 GroupDefinition groupDefinition = allGroups.get(groupName);
1672 // All Members Of Current Group Resource Instances & Other Groups
1673 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1674 // Filtered Members Of Current Group containing only members which
1676 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1677 // Keep Only Elements of type group and not Resource Instances
1678 filter(allGroups::containsKey).
1679 // Add Filtered Elements to main Set
1680 peek(allGroupMembers::add).
1684 // Recursively call the method for all the filtered group members
1685 for (String innerGroupName : currGroupFilteredMembers) {
1686 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1691 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
1692 Set<String> allGroupMembers) {
1694 boolean stop = false;
1695 // In Case Not Group Stop
1696 if (!allGroups.containsKey(groupName)) {
1699 // In Case Group Has no members stop
1701 GroupDefinition groupDefinition = allGroups.get(groupName);
1702 stop = isEmpty(groupDefinition.getMembers());
1705 // In Case all group members already contained stop
1707 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1708 Set<String> membersOfTypeGroup = allMembers.stream().
1709 // Filter In Only Group members
1710 filter(allGroups::containsKey).
1713 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1718 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1719 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1720 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1721 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1722 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1725 log.debug("************* Going to create all nodes {}", yamlName);
1726 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1727 nodeTypesInfo, csarInfo, nodeName);
1728 log.debug("************* Finished to create all nodes {}", yamlName);
1729 log.debug("************* Going to create all resource instances {}", yamlName);
1730 resource = createResourceInstances(yamlName, resource,
1731 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1732 log.debug("************* Finished to create all resource instances {}", yamlName);
1733 log.debug("************* Going to create all relations {}", yamlName);
1734 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1735 log.debug("************* Finished to create all relations {}", yamlName);
1736 log.debug("************* Going to create positions {}", yamlName);
1737 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1738 log.debug("************* Finished to set positions {}", yamlName);
1742 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
1743 List<ArtifactDefinition> artifactsToAdd) {
1744 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
1746 artifactsToAdd.stream().forEach(a -> {
1747 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1748 vfcArtifacts.add(a);
1750 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1756 @SuppressWarnings("unchecked")
1757 private void handleNodeTypes(String yamlName, Resource resource,
1758 String topologyTemplateYaml, boolean needLock,
1759 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1760 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1761 CsarInfo csarInfo, String nodeName) {
1763 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1764 if (nodeTypeEntry.getValue().isNested()) {
1766 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1767 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1768 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1771 Map<String, Object> mappedToscaTemplate = null;
1772 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
1773 && nodeTypesInfo.containsKey(nodeName)) {
1774 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1776 if (isEmpty(mappedToscaTemplate)) {
1777 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1779 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1780 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1781 } catch(ComponentException e){
1782 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
1783 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1784 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1786 } catch (StorageException e){
1787 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1788 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1791 // add the created node types to the cache although they are not in the
1793 csarInfo.getCreatedNodes().values().stream()
1794 .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1797 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
1798 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1799 boolean inTransaction) {
1801 if (csarInfo.getCsar() != null) {
1802 String vendorLicenseModelId = null;
1803 String vfLicenseModelId = null;
1805 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1806 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1807 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1808 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1809 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1810 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1812 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1813 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1819 // Specific Behavior for license artifacts
1820 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1821 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
1822 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1823 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
1824 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
1826 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1827 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1828 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1829 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
1830 artifactOperation, null, true, shouldLock, inTransaction);
1832 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
1833 createdArtifacts, shouldLock, inTransaction, artifactOperation);
1834 if (eitherCreateResult.isRight()) {
1835 return Either.right(eitherCreateResult.right().value());
1837 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1838 .getToscaElement(resource.getUniqueId());
1839 if (eitherGerResource.isRight()) {
1840 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1841 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1843 return Either.right(responseFormat);
1846 resource = eitherGerResource.left().value();
1848 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1850 if (artifacsMetaCsarStatus.isLeft()) {
1851 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1852 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1853 Either<Resource, ResponseFormat> createArtifactsFromCsar;
1854 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1855 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1857 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1860 if (createArtifactsFromCsar.isRight()) {
1861 log.debug("Couldn't create artifacts from artifacts.meta");
1862 return Either.right(createArtifactsFromCsar.right().value());
1865 return Either.left(createArtifactsFromCsar.left().value());
1868 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
1872 return Either.left(resource);
1876 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
1877 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1878 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1879 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1880 boolean inTransaction) {
1881 byte[] artifactFileBytes = null;
1883 if (csarInfo.getCsar().containsKey(artifactPath)) {
1884 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1886 Either<Boolean, ResponseFormat> result = Either.left(true);
1887 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
1888 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1889 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
1890 shouldLock, inTransaction);
1891 if (handleDelete.isRight()) {
1892 result = Either.right(handleDelete.right().value());
1898 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1899 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1900 ArtifactOperationEnum.CREATE);
1904 if (artifactFileBytes != null) {
1905 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1906 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1907 artifactFileBytes, null, isFromCsar);
1908 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1909 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1910 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1911 if (eitherNonMetaArtifacts.isRight()) {
1912 BeEcompErrorManager.getInstance()
1913 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1914 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1915 ErrorSeverity.WARNING);
1916 return Either.right(eitherNonMetaArtifacts.right().value());
1922 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
1923 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
1927 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
1928 List<ArtifactDefinition> createdArtifacts,
1929 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
1930 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
1931 && eitherNonMetaArtifacts.isLeft()) {
1932 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
1933 if (eitherResult.isLeft()) {
1934 createdArtifacts.add(eitherResult.left().value());
1940 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
1941 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
1942 ArtifactOperationInfo artifactOperation) {
1944 Either<Resource, ResponseFormat> resStatus = null;
1945 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
1948 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
1949 if (artifactPathAndNameList.isRight()) {
1950 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
1951 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
1953 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
1955 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1956 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
1957 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
1959 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
1960 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
1962 if (findVfCsarArtifactsToHandleRes.isRight()) {
1963 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
1965 if (resStatus == null) {
1966 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
1969 if (resStatus == null && vfCsarArtifactsToHandle != null) {
1970 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
1972 if (resStatus == null) {
1973 resStatus = Either.left(resource);
1975 } catch (Exception e) {
1976 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1977 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
1979 CsarUtils.handleWarningMessages(collectedWarningMessages);
1984 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) {
1985 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
1988 Optional<ResponseFormat> optionalCreateInDBError =
1989 // Stream of artifacts to be created
1990 currArtifactOperationPair.getValue().stream()
1991 // create each artifact
1992 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
1993 e.getArtifactName(), e.getArtifactType().getType(),
1994 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
1995 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
1996 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1997 currArtifactOperationPair.getKey()),
1998 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
1999 // filter in only error
2000 .filter(Either::isRight).
2001 // Convert the error from either to
2003 map(e -> e.right().value()).
2004 // Check if an error occurred
2006 // Error found on artifact Creation
2007 if (optionalCreateInDBError.isPresent()) {
2008 resStatus = Either.right(optionalCreateInDBError.get());
2015 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
2016 List<NonMetaArtifactInfo> artifactPathAndNameList =
2017 // Stream of file paths contained in csar
2018 csarInfo.getCsar().entrySet().stream()
2019 // Filter in only VF artifact path location
2020 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2022 // Validate and add warnings
2023 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2024 collectedWarningMessages))
2025 // Filter in Non Warnings
2026 .filter(Either::isLeft)
2027 // Convert from Either to NonMetaArtifactInfo
2028 .map(e -> e.left().value())
2031 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2032 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2033 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2034 return Either.right(nonMetaArtifactInfo.getArtifactName());
2037 return Either.left(artifactPathAndNameList);
2040 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2041 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2043 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2044 // collect all Deployment and Informational artifacts of VF
2045 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2046 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2048 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2049 existingArtifacts.addAll(resource.getArtifacts().values());
2051 existingArtifacts = existingArtifacts.stream()
2052 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2053 // was created from HEAT.meta
2054 .filter(this::isNonMetaArtifact).collect(toList());
2056 List<String> artifactsToIgnore = new ArrayList<>();
2057 // collect IDs of Artifacts of VF which belongs to any group
2058 if (resource.getGroups() != null) {
2059 resource.getGroups().stream().forEach(g -> {
2060 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
2061 artifactsToIgnore.addAll(g.getArtifacts());
2065 existingArtifacts = existingArtifacts.stream()
2066 // filter artifacts which belongs to any group
2067 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
2068 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2071 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2072 boolean result = true;
2073 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2079 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2080 boolean result = true;
2081 if (artifact.getArtifactType() == null
2082 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2083 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2089 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
2090 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2091 log.debug("#createResourceInstancesRelations - Going to create relations ");
2092 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2093 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) {
2094 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
2095 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations","No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2096 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
2098 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2099 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2100 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2101 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2102 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2103 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2104 Map<String, Resource> originCompMap = new HashMap<>();
2105 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2106 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2108 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2109 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2110 if (allDataTypes.isRight()) {
2111 TitanOperationStatus status = allDataTypes.right().value();
2112 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2113 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2114 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2115 DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
2118 Resource finalResource = resource;
2119 uploadResInstancesMap
2121 .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2122 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
2123 instArtifacts, instAttributes, originCompMap, instInputs, i));
2125 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2126 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2127 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2128 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2129 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2130 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2132 resource = getResourceAfterCreateRelations(resource);
2134 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2135 associateResourceInstances(yamlName, resource, relations);
2136 handleSubstitutionMappings(resource, uploadResInstancesMap);
2137 log.debug("************* in create relations, getResource start");
2138 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2139 log.debug("************* in create relations, getResource end");
2140 if (eitherGetResource.isRight()) {
2141 throw new ComponentException(componentsUtils.getResponseFormatByResource(
2142 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
2144 return eitherGetResource.left().value();
2147 private Resource getResourceAfterCreateRelations(Resource resource) {
2148 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2149 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2150 .getToscaElement(resource.getUniqueId(), parametersView);
2152 if (eitherGetResource.isRight()) {
2153 throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2155 return eitherGetResource.left().value();
2158 private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2159 StorageOperationStatus addArtToInst;
2160 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2161 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2162 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2164 throw new ComponentException(componentsUtils
2165 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2169 private ComponentParametersView getComponentFilterAfterCreateRelations() {
2170 ComponentParametersView parametersView = new ComponentParametersView();
2171 parametersView.disableAll();
2172 parametersView.setIgnoreComponentInstances(false);
2173 parametersView.setIgnoreComponentInstancesProperties(false);
2174 parametersView.setIgnoreCapabilities(false);
2175 parametersView.setIgnoreRequirements(false);
2176 parametersView.setIgnoreGroups(false);
2177 return parametersView;
2180 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
2181 StorageOperationStatus addArtToInst;
2182 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2183 resource.getUniqueId());
2184 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2185 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2187 throw new ComponentException(componentsUtils
2188 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2192 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2193 StorageOperationStatus addArtToInst;
2194 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2195 resource.getUniqueId());
2196 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2197 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2199 throw new ComponentException(componentsUtils
2200 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2204 private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2205 StorageOperationStatus addArtToInst;
2207 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
2208 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2209 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2210 throw new ComponentException(componentsUtils
2211 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2215 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2216 StorageOperationStatus addArtToInst = toscaOperationFacade
2217 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2218 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2219 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2220 throw new ComponentException(componentsUtils
2221 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2225 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2226 if (MapUtils.isNotEmpty(instInputs)) {
2227 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2228 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2229 if (addInputToInst.isRight()) {
2230 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2231 addInputToInst.right().value());
2232 throw new ComponentException(componentsUtils.getResponseFormat(
2233 componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2238 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2239 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2240 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2241 if (addPropToInst.isRight()) {
2242 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2243 addPropToInst.right().value());
2244 throw new ComponentException(componentsUtils.getResponseFormat(
2245 componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2249 private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2250 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2251 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2252 if (getResourceRes.isRight()) {
2253 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2254 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2255 throw new ComponentException(responseFormat);
2257 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2258 uploadResInstancesMap);
2259 if (getResourceRes.isRight()) {
2260 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2261 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2262 throw new ComponentException(responseFormat);
2267 private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2268 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2269 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2270 ComponentInstance currentCompInstance = null;
2271 for (ComponentInstance compInstance : componentInstancesList) {
2273 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2274 currentCompInstance = compInstance;
2279 if (currentCompInstance == null) {
2280 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2281 resource.getUniqueId());
2282 BeEcompErrorManager.getInstance().logInternalDataError(
2283 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2284 resource.getUniqueId(), ErrorSeverity.ERROR);
2285 ResponseFormat responseFormat = componentsUtils
2286 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2287 throw new ComponentException(responseFormat);
2290 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2291 if (addRelationToRiRes.getStatus() != 200) {
2292 throw new ComponentException(addRelationToRiRes);
2297 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) {
2298 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2299 .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
2301 if (!currentCompInstanceOpt.isPresent()) {
2302 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2303 resource.getUniqueId());
2304 BeEcompErrorManager.getInstance().logInternalDataError(
2305 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2306 resource.getUniqueId(), ErrorSeverity.ERROR);
2307 ResponseFormat responseFormat = componentsUtils
2308 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2309 throw new ComponentException(responseFormat);
2311 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2312 String resourceInstanceId = currentCompInstance.getUniqueId();
2313 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
2314 if (isNotEmpty(originResource.getRequirements())) {
2315 instRequirements.put(currentCompInstance, originResource.getRequirements());
2317 if (isNotEmpty(originResource.getCapabilities())) {
2318 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2319 currentCompInstance, originResource);
2321 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
2322 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2324 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2325 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2327 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2328 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2330 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2331 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2332 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
2333 if (addPropertiesValueToRiRes.getStatus() != 200) {
2334 throw new ComponentException(addPropertiesValueToRiRes);
2337 addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2338 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
2342 private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2343 Resource originResource;
2344 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2345 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2346 .getToscaFullElement(currentCompInstance.getComponentUid());
2347 if (getOriginResourceRes.isRight()) {
2348 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2349 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2350 getOriginResourceRes);
2351 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2352 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2353 throw new ComponentException(responseFormat);
2355 originResource = getOriginResourceRes.left().value();
2356 originCompMap.put(originResource.getUniqueId(), originResource);
2358 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2360 return originResource;
2363 private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2364 Map<String, List<CapabilityDefinition>> originCapabilities;
2365 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2366 originCapabilities = new HashMap<>();
2367 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2368 originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v));
2369 uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
2370 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2372 originCapabilities = originResource.getCapabilities();
2374 instCapabilties.put(currentCompInstance, originCapabilities);
2377 private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2378 originCapabilities.values().stream()
2379 .flatMap(Collection::stream)
2380 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2381 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2384 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2385 for (UploadCapInfo capability : capabilities) {
2386 if (isNotEmpty(capability.getProperties())) {
2387 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2388 .collect(toMap(UploadInfo::getName, p -> p)));
2393 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2394 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2396 originCapabilities.put(type, list);
2399 private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2400 Map<String, DataTypeDefinition> allDataTypes) {
2401 properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2404 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2405 Map<String, DataTypeDefinition> allDataTypes) {
2406 String value = null;
2407 List<GetInputValueDataDefinition> getInputs = null;
2408 boolean isValidate = true;
2409 if (null != propertyInfo && propertyInfo.getValue() != null) {
2410 getInputs = propertyInfo.getGet_input();
2411 isValidate = getInputs == null || getInputs.isEmpty();
2413 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2415 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2416 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2419 property.setValue(value);
2420 return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2423 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2424 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2425 Either<Resource, StorageOperationStatus> updateRes = null;
2426 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2427 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2428 StorageOperationStatus status = toscaOperationFacade
2429 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2430 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2432 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2433 resource.getUniqueId(), status);
2434 updateRes = Either.right(status);
2436 if (updateRes == null) {
2437 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2438 updatedInstCapabilities, updatedInstRequirements);
2439 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2440 resource.getUniqueId());
2441 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2443 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2444 resource.getUniqueId(), status);
2445 updateRes = Either.right(status);
2448 if (updateRes == null) {
2449 updateRes = Either.left(resource);
2454 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2455 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2456 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2457 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2459 componentInstances.stream().forEach(i -> {
2460 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2461 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2462 fillUpdatedInstRequirements(updatedInstRequirements, i,
2463 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2467 private void fillUpdatedInstRequirements(
2468 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2469 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2470 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2471 Set<String> updatedReqNames = new HashSet<>();
2472 if (isNotEmpty(requirementsNamesToUpdate)) {
2473 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2474 updatedRequirements.put(requirements.getKey(),
2475 requirements.getValue().stream()
2476 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2477 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2479 r.setParentName(r.getName());
2480 r.setName(requirementsNamesToUpdate.get(r.getName()));
2481 updatedReqNames.add(r.getName());
2483 }).collect(toList()));
2486 if (isNotEmpty(updatedRequirements)) {
2487 updatedInstRequirements.put(instance, updatedRequirements);
2491 private void fillUpdatedInstCapabilities(
2492 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2493 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2494 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2495 Set<String> updatedCapNames = new HashSet<>();
2496 if (isNotEmpty(capabilitiesNamesToUpdate)) {
2497 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2498 updatedCapabilities.put(requirements.getKey(),
2499 requirements.getValue().stream()
2500 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2501 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2503 c.setParentName(c.getName());
2504 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2505 updatedCapNames.add(c.getName());
2507 }).collect(toList()));
2510 if (isNotEmpty(updatedCapabilities)) {
2511 updatedInstCapabilties.put(instance, updatedCapabilities);
2515 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2516 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2517 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2519 ComponentInstance currentCompInstance = null;
2521 for (ComponentInstance compInstance : componentInstancesList) {
2523 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2524 currentCompInstance = compInstance;
2530 if (currentCompInstance == null) {
2531 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2532 resource.getUniqueId());
2533 BeEcompErrorManager.getInstance().logInternalDataError(
2534 COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2535 resource.getUniqueId(), ErrorSeverity.ERROR);
2536 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2539 String resourceInstanceId = currentCompInstance.getUniqueId();
2541 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2543 if (regMap != null) {
2544 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2546 while (nodesRegValue.hasNext()) {
2547 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2549 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2550 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2551 log.debug("Going to create relation {}", uploadRegInfo.getName());
2552 String regName = uploadRegInfo.getName();
2553 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2554 regCapRelDef.setFromNode(resourceInstanceId);
2555 log.debug("try to find available requirement {} ", regName);
2556 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2557 yamlName, nodesInfoValue, currentCompInstance,
2558 uploadRegInfo.getCapabilityName());
2559 if (eitherReqStatus.isRight()) {
2560 log.debug("failed to find available requirement {} status is {}", regName,
2561 eitherReqStatus.right().value());
2562 return eitherReqStatus.right().value();
2565 RequirementDefinition validReq = eitherReqStatus.left().value();
2566 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2567 .getRelationships();
2568 if (reqAndRelationshipPairList == null) {
2569 reqAndRelationshipPairList = new ArrayList<>();
2571 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2572 reqAndRelationshipPair.setRequirement(regName);
2573 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2574 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2575 RelationshipImpl relationship = new RelationshipImpl();
2576 relationship.setType(validReq.getCapability());
2577 reqAndRelationshipPair.setRelationships(relationship);
2579 ComponentInstance currentCapCompInstance = null;
2580 for (ComponentInstance compInstance : componentInstancesList) {
2581 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2582 currentCapCompInstance = compInstance;
2587 if (currentCapCompInstance == null) {
2588 log.debug("The component instance with name {} not found on resource {} ",
2589 uploadRegInfo.getNode(), resource.getUniqueId());
2590 BeEcompErrorManager.getInstance().logInternalDataError(
2591 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2592 resource.getUniqueId(), ErrorSeverity.ERROR);
2593 return componentsUtils
2594 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2596 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2597 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2598 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2599 currentCapCompInstance, uploadRegInfo);
2600 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2601 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2602 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2603 if (aviableCapForRel == null) {
2604 log.debug("aviable capability was not found. req name is {} component instance is {}",
2605 validReq.getName(), currentCapCompInstance.getUniqueId());
2606 BeEcompErrorManager.getInstance().logInternalDataError(
2607 "aviable capability was not found. req name is " + validReq.getName()
2608 + " component instance is " + currentCapCompInstance.getUniqueId(),
2609 resource.getUniqueId(), ErrorSeverity.ERROR);
2610 return componentsUtils
2611 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2613 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2614 capReqRel.setRelation(reqAndRelationshipPair);
2615 reqAndRelationshipPairList.add(capReqRel);
2616 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2617 relations.add(regCapRelDef);
2620 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
2621 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2623 return componentsUtils.getResponseFormat(ActionStatus.OK);
2626 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2627 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2628 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
2629 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2630 if (MapUtils.isNotEmpty(propMap)) {
2631 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2632 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2634 if (CollectionUtils.isEmpty( originResource.getInputs())) {
2635 log.debug("failed to find properties ");
2636 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2638 originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
2639 for (List<UploadPropInfo> propertyList : propMap.values()) {
2640 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
2642 currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
2643 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2647 private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
2648 UploadPropInfo propertyInfo = propertyList.get(0);
2649 String propName = propertyInfo.getName();
2650 if (!currPropertiesMap.containsKey(propName)) {
2651 log.debug("failed to find property {} ", propName);
2652 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2655 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
2656 ComponentInstanceInput property = null;
2658 String value = null;
2659 List<GetInputValueDataDefinition> getInputs = null;
2660 boolean isValidate = true;
2661 if (propertyInfo.getValue() != null) {
2662 getInputs = propertyInfo.getGet_input();
2663 isValidate = getInputs == null || getInputs.isEmpty();
2665 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2666 curPropertyDef.getType());
2668 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2669 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2672 String innerType = null;
2673 property = new ComponentInstanceInput(curPropertyDef, value, null);
2675 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2677 property.setValue(validPropertyVAlue);
2679 if (isNotEmpty(getInputs)) {
2680 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2681 for (GetInputValueDataDefinition getInput : getInputs) {
2682 List<InputDefinition> inputs = resource.getInputs();
2683 if (CollectionUtils.isEmpty(inputs)) {
2684 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
2685 property, currentCompInstance.getUniqueId());
2686 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2689 Optional<InputDefinition> optional = inputs.stream()
2690 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
2691 if (!optional.isPresent()) {
2692 log.debug("Failed to find input {} ", getInput.getInputName());
2693 // @@TODO error message
2694 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2696 InputDefinition input = optional.get();
2697 getInput.setInputId(input.getUniqueId());
2698 getInputValues.add(getInput);
2700 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2701 processGetInput(getInputValues, inputs, getInputIndex);
2703 property.setGetInputValues(getInputValues);
2705 instPropList.add(property);
2706 // delete overriden property
2707 currPropertiesMap.remove(property.getName());
2710 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
2711 Optional<InputDefinition> optional;
2712 if (getInputIndex != null) {
2713 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
2715 if (!optional.isPresent()) {
2716 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2717 // @@TODO error message
2718 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2720 InputDefinition inputIndex = optional.get();
2721 getInputIndex.setInputId(inputIndex.getUniqueId());
2722 getInputValues.add(getInputIndex);
2726 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
2727 String propName = prop.getName();
2728 if (!currPropertiesMap.containsKey(propName)) {
2729 currPropertiesMap.put(propName, prop);
2733 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2734 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2735 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
2737 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2738 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2740 List<PropertyDefinition> listFromMap = originResource.getProperties();
2741 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
2742 log.debug("failed to find properties ");
2743 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2745 if (listFromMap == null || listFromMap.isEmpty()) {
2746 return componentsUtils.getResponseFormat(ActionStatus.OK);
2748 for (PropertyDefinition prop : listFromMap) {
2749 String propName = prop.getName();
2750 if (!currPropertiesMap.containsKey(propName)) {
2751 currPropertiesMap.put(propName, prop);
2754 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2755 if (propMap != null && propMap.size() > 0) {
2756 for (List<UploadPropInfo> propertyList : propMap.values()) {
2758 UploadPropInfo propertyInfo = propertyList.get(0);
2759 String propName = propertyInfo.getName();
2760 if (!currPropertiesMap.containsKey(propName)) {
2761 log.debug("failed to find property {} ", propName);
2762 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2765 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2766 ComponentInstanceProperty property = null;
2768 String value = null;
2769 List<GetInputValueDataDefinition> getInputs = null;
2770 boolean isValidate = true;
2771 if (propertyInfo.getValue() != null) {
2772 getInputs = propertyInfo.getGet_input();
2773 isValidate = getInputs == null || getInputs.isEmpty();
2775 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2776 curPropertyDef.getType());
2778 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2779 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2782 String innerType = null;
2783 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2785 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2786 property.setValue(validatePropValue);
2788 if (getInputs != null && !getInputs.isEmpty()) {
2789 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2790 for (GetInputValueDataDefinition getInput : getInputs) {
2791 List<InputDefinition> inputs = resource.getInputs();
2792 if (inputs == null || inputs.isEmpty()) {
2793 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2794 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2796 .map(GetInputValueDataDefinition::getInputName)
2797 .collect(toList()).toString());
2799 InputDefinition input = findInputByName(inputs, getInput);
2800 getInput.setInputId(input.getUniqueId());
2801 getInputValues.add(getInput);
2803 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2804 if (getInputIndex != null) {
2805 input = findInputByName(inputs, getInputIndex);
2806 getInputIndex.setInputId(input.getUniqueId());
2807 getInputValues.add(getInputIndex);
2812 property.setGetInputValues(getInputValues);
2814 instPropList.add(property);
2815 // delete overriden property
2816 currPropertiesMap.remove(property.getName());
2819 // add rest of properties
2820 if (!currPropertiesMap.isEmpty()) {
2821 for (PropertyDefinition value : currPropertiesMap.values()) {
2822 instPropList.add(new ComponentInstanceProperty(value));
2825 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2826 return componentsUtils.getResponseFormat(ActionStatus.OK);
2829 // US740820 Relate RIs according to capability name
2830 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
2831 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2832 if (null == uploadReqInfo.getCapabilityName()
2833 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
2837 return findAvailableCapability(validReq, currentCapCompInstance);
2839 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
2842 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
2843 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2844 CapabilityDefinition cap = null;
2845 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
2846 if (!capMap.containsKey(validReq.getCapability())) {
2849 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
2850 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
2851 if (!capByName.isPresent()) {
2854 cap = capByName.get();
2856 if (isBoundedByOccurrences(cap)) {
2857 String leftOccurrences = cap.getLeftOccurrences();
2858 int left = Integer.parseInt(leftOccurrences);
2861 cap.setLeftOccurrences(String.valueOf(left));
2869 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
2870 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
2871 if (capMap.containsKey(validReq.getCapability())) {
2872 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
2874 for (CapabilityDefinition cap : capList) {
2875 if (isBoundedByOccurrences(cap)) {
2876 String leftOccurrences = cap.getLeftOccurrences() != null ?
2877 cap.getLeftOccurrences() : cap.getMaxOccurrences();
2878 int left = Integer.parseInt(leftOccurrences);
2881 cap.setLeftOccurrences(String.valueOf(left));
2892 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
2893 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
2896 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
2897 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2899 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
2900 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
2901 RequirementDefinition validRegDef = null;
2903 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
2904 for (RequirementDefinition reqDef : entry.getValue()) {
2905 if (reqDef.getName().equals(regName)) {
2906 if (reqDef.getMaxOccurrences() != null
2907 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2908 String leftOccurrences = reqDef.getLeftOccurrences();
2909 if (leftOccurrences == null) {
2910 leftOccurrences = reqDef.getMaxOccurrences();
2912 int left = Integer.parseInt(leftOccurrences);
2915 reqDef.setLeftOccurrences(String.valueOf(left));
2916 validRegDef = reqDef;
2922 validRegDef = reqDef;
2928 if (validRegDef != null) {
2933 for (RequirementDefinition reqDef : list) {
2934 if (reqDef.getName().equals(regName)) {
2935 if (reqDef.getMaxOccurrences() != null
2936 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2937 String leftOccurrences = reqDef.getLeftOccurrences();
2938 if (leftOccurrences == null) {
2939 leftOccurrences = reqDef.getMaxOccurrences();
2941 int left = Integer.parseInt(leftOccurrences);
2944 reqDef.setLeftOccurrences(String.valueOf(left));
2945 validRegDef = reqDef;
2951 validRegDef = reqDef;
2957 if (validRegDef == null) {
2958 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2959 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2960 return Either.right(responseFormat);
2962 return Either.left(validRegDef);
2965 private Resource createResourceInstances(String yamlName, Resource resource,
2966 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2967 Map<String, Resource> nodeNamespaceMap) {
2969 Either<Resource, ResponseFormat> eitherResource = null;
2970 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2971 if (isEmpty(uploadResInstancesMap)) {
2972 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2973 throw new ComponentException(responseFormat);
2975 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2976 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2977 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2979 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2980 uploadResInstancesMap
2982 .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2984 if (isNotEmpty(resourcesInstancesMap)) {
2985 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
2986 resourcesInstancesMap, false);
2987 if (status != null && status != StorageOperationStatus.OK) {
2988 log.debug("Failed to add component instances to container component {}", resource.getName());
2989 ResponseFormat responseFormat = componentsUtils
2990 .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
2991 eitherResource = Either.right(responseFormat);
2992 throw new ComponentException(eitherResource.right().value());
2995 log.debug("*************Going to get resource {}", resource.getUniqueId());
2996 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2997 .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
2998 log.debug("*************finished to get resource {}", resource.getUniqueId());
2999 if (eitherGetResource.isRight()) {
3000 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3001 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3002 throw new ComponentException(responseFormat);
3004 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) {
3005 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3006 BeEcompErrorManager.getInstance().logBeDaoSystemError(
3007 "Error when create resource instance from csar. ComponentInstances list empty");
3008 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3010 return eitherGetResource.left().value();
3013 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3014 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
3015 Either<Resource, ResponseFormat> eitherResource;
3016 log.debug("*************Going to create resource instances {}", yamlName);
3017 // updating type if the type is node type name - we need to take the
3019 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3020 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3021 uploadComponentInstanceInfo
3022 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3024 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3025 existingnodeTypeMap);
3027 ComponentInstance componentInstance = new ComponentInstance();
3028 componentInstance.setComponentUid(refResource.getUniqueId());
3029 ComponentTypeEnum containerComponentType = resource.getComponentType();
3030 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3031 if (containerNodeType.equals(NodeTypeEnum.Resource)
3032 && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3033 && isNotEmpty(refResource.getCapabilities())) {
3034 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3035 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3036 refResource.getUniqueId(), refResource.getCapabilities(),
3037 uploadComponentInstanceInfo.getCapabilities());
3038 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3040 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3042 "createResourceInstances - not found lates version for resource instance with name {} and type ",
3043 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3044 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3045 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3046 throw new ComponentException(responseFormat);
3048 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3049 componentInstance.setName(uploadComponentInstanceInfo.getName());
3050 componentInstance.setIcon(origResource.getIcon());
3051 resourcesInstancesMap.put(componentInstance, origResource);
3054 private ComponentParametersView getComponentWithInstancesFilter() {
3055 ComponentParametersView parametersView = new ComponentParametersView();
3056 parametersView.disableAll();
3057 parametersView.setIgnoreComponentInstances(false);
3058 parametersView.setIgnoreInputs(false);
3059 // inputs are read when creating
3060 // property values on instances
3061 parametersView.setIgnoreUsers(false);
3062 return parametersView;
3065 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3066 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3067 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3068 if (originCapabilities.containsKey(currEntry.getKey())) {
3069 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3072 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3073 capabilities.getValue().stream().forEach(cap -> {
3074 if (uploadedCapabilities.containsKey(cap.getName())) {
3075 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3076 c.setName(cap.getName());
3077 c.setType(cap.getType());
3085 private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
3086 Map<String, Resource> nodeNamespaceMap) {
3088 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3089 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3090 Resource refResource;
3091 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3092 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3094 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3095 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3096 if (findResourceEither.isRight()) {
3098 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3099 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3100 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3101 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3102 throw new ComponentException(responseFormat);
3104 refResource = findResourceEither.left().value();
3105 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3107 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3108 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3110 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3111 refResource.getName(), componentState);
3112 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3113 refResource.getComponentType().getValue(), refResource.getName(), componentState);
3114 throw new ComponentException(responseFormat);
3117 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3118 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3119 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3120 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3121 throw new ComponentException(responseFormat);
3127 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
3128 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3129 boolean forceCertificationAllowed) {
3131 Either<Resource, ResponseFormat> result = null;
3133 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3134 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3135 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3136 if (result.isRight()) {
3139 resource = result.left().value();
3141 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3142 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
3143 resource, user, false, inTransaction, needLock);
3144 result = eitherPopulated.isLeft() ? Either.left(resource)
3145 : Either.right(eitherPopulated.right().value());
3148 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3149 } catch (Exception e) {
3150 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3151 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3153 if (result == null || result.isRight()) {
3154 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3155 if (!inTransaction) {
3156 titanDao.rollback();
3158 } else if (!inTransaction) {
3164 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
3165 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3166 return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
3167 lifecycleChangeInfo, inTransaction, needLock);
3170 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
3171 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3172 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3176 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
3177 Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
3178 CsarInfo csarInfo, String nodeName, boolean isNested) {
3180 ImmutablePair<Resource, ActionStatus> result = null;
3181 // check if resource already exists (search by tosca name = type)
3182 boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3183 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3184 .getLatestByToscaResourceName(resource.getToscaResourceName());
3186 if (latestByToscaName.isLeft()) {
3187 Resource foundResource = latestByToscaName.left().value();
3188 // we don't allow updating names of top level types
3189 if (!isNestedResource &&
3190 !StringUtils.equals(resource.getName(), foundResource.getName())) {
3191 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3192 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3193 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3194 foundResource.getName(), resource.getToscaResourceName());
3195 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3196 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3197 throwComponentException(responseFormat);
3199 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3200 } else if (isNotFound(latestByToscaName)) {
3201 if (isNestedResource) {
3202 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
3204 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3207 StorageOperationStatus status = latestByToscaName.right().value();
3208 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3209 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3210 componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
3211 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3212 throwComponentException(responseFormat);
3217 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3218 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3221 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
3222 Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
3223 resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
3224 if (latestByToscaName.isLeft()) {
3225 Resource nestedResource = (Resource) latestByToscaName.left().value();
3226 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3227 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
3228 ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3229 if (eitherValidation.isRight()) {
3230 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3232 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3234 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3238 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3239 return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
3242 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
3243 User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3244 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3245 validateResourceBeforeCreate(resource, user,
3246 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3247 Resource createdResource = createResourceByDao(resource, user,
3248 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
3249 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
3250 ActionStatus.CREATED);
3251 ASDCKpiApi.countImportResourcesKPI();
3252 return resourcePair;
3255 public boolean isResourceExist(String resourceName) {
3256 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3257 return latestByName.isLeft();
3260 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3261 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3263 String lockedResourceId = oldResource.getUniqueId();
3264 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3265 oldResource.getVersion(), oldResource.getLifecycleState());
3266 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3268 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3269 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3270 mergeOldResourceMetadataWithNew(oldResource, newResource);
3272 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3273 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3274 // contact info normalization
3275 newResource.setContactId(newResource.getContactId().toLowerCase());
3276 // non-updatable fields
3277 newResource.setCreatorUserId(user.getUserId());
3278 newResource.setCreatorFullName(user.getFullName());
3279 newResource.setLastUpdaterUserId(user.getUserId());
3280 newResource.setLastUpdaterFullName(user.getFullName());
3281 newResource.setUniqueId(oldResource.getUniqueId());
3282 newResource.setVersion(oldResource.getVersion());
3283 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3284 newResource.setLifecycleState(oldResource.getLifecycleState());
3285 newResource.setUUID(oldResource.getUUID());
3286 newResource.setNormalizedName(oldResource.getNormalizedName());
3287 newResource.setSystemName(oldResource.getSystemName());
3288 if (oldResource.getCsarUUID() != null) {
3289 newResource.setCsarUUID(oldResource.getCsarUUID());
3291 if (oldResource.getImportedToscaChecksum() != null) {
3292 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3294 newResource.setAbstract(oldResource.isAbstract());
3296 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
3297 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3299 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3300 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3302 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3303 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3306 // created without tosca artifacts - add the placeholders
3307 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3308 setToscaArtifactsPlaceHolders(newResource, user);
3311 if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) {
3312 newResource.setInterfaces(oldResource.getInterfaces());
3315 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3316 .overrideComponent(newResource, oldResource);
3318 if (overrideResource.isRight()) {
3319 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3320 componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3321 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3323 throwComponentException(responseFormat);
3326 log.debug("Resource updated successfully!!!");
3327 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3328 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3329 ResourceVersionInfo.newBuilder()
3330 .state(oldResource.getLifecycleState()
3332 .version(oldResource.getVersion())
3335 resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3337 return resourcePair;
3339 if (resourcePair == null) {
3340 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3341 titanDao.rollback();
3342 } else if (!inTransaction) {
3346 log.debug("unlock resource {}", lockedResourceId);
3347 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3354 * Merge old resource with new. Keep old category and vendor name without
3357 * @param oldResource
3358 * @param newResource
3360 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3362 // keep old category and vendor name without change
3363 // merge the rest of the resource metadata
3364 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3365 newResource.setTags(oldResource.getTags());
3368 if (newResource.getDescription() == null) {
3369 newResource.setDescription(oldResource.getDescription());
3372 if (newResource.getVendorRelease() == null) {
3373 newResource.setVendorRelease(oldResource.getVendorRelease());
3376 if (newResource.getResourceVendorModelNumber() == null) {
3377 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3380 if (newResource.getContactId() == null) {
3381 newResource.setContactId(oldResource.getContactId());
3384 newResource.setCategories(oldResource.getCategories());
3385 if (newResource.getVendorName() == null) {
3386 newResource.setVendorName(oldResource.getVendorName());
3390 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3391 boolean inTransaction, boolean needLock) {
3393 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3395 return lifecycleBusinessLogic.changeState(
3396 oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3397 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3399 .on(response -> failOnChangeState(response, user, oldResource, newResource));
3404 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3405 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3406 response.getFormattedMessage());
3407 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3408 ResourceVersionInfo.newBuilder()
3409 .state(oldResource.getLifecycleState().name())
3410 .version(oldResource.getVersion())
3412 throw new ComponentException(response);
3415 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3417 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3418 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3419 validateLifecycleTypesCreate(user, resource, actionEnum);
3420 validateResourceType(user, resource, actionEnum);
3421 resource.setCreatorUserId(user.getUserId());
3422 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3423 resource.setContactId(resource.getContactId().toLowerCase());
3424 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3425 String resourceSystemName;
3426 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3427 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3429 resourceSystemName = resource.getSystemName();
3431 resource.setToscaResourceName(CommonBeUtils
3432 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3435 // Generate invariant UUID - must be here and not in operation since it
3436 // should stay constant during clone
3438 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3439 resource.setInvariantUUID(invariantUUID);
3444 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3445 AuditingActionEnum actionEnum) {
3446 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3447 if (resource.getResourceType() == null) {
3448 log.debug("Invalid resource type for resource");
3449 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3450 eitherResult = Either.right(errorResponse);
3451 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3453 return eitherResult;
3456 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3457 AuditingActionEnum actionEnum) {
3458 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3459 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3460 log.debug("validate interface lifecycle Types Exist");
3461 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3462 while (intItr.hasNext() && eitherResult.isLeft()) {
3463 InterfaceDefinition interfaceDefinition = intItr.next();
3464 String intType = interfaceDefinition.getUniqueId();
3465 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3466 .getInterface(intType);
3467 if (eitherCapTypeFound.isRight()) {
3468 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3469 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3470 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3471 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3472 intType, resource.getName());
3473 BeEcompErrorManager.getInstance()
3474 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3475 log.debug("request to data model failed with error: {}",
3476 eitherCapTypeFound.right().value().name());
3479 ResponseFormat errorResponse = componentsUtils
3480 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3481 eitherResult = Either.right(errorResponse);
3482 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3487 return eitherResult;
3490 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3491 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3492 boolean inTransaction) {
3494 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3495 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3496 log.debug("validate capability Types Exist - capabilities section");
3498 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3500 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3501 eitherResult, typeEntry, inTransaction);
3502 if (eitherResult.isRight()) {
3503 return Either.right(eitherResult.right().value());
3508 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3509 log.debug("validate capability Types Exist - requirements section");
3510 for (String type : resource.getRequirements().keySet()) {
3511 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3512 resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3513 if (eitherResult.isRight()) {
3514 return Either.right(eitherResult.right().value());
3519 return eitherResult;
3522 // @param typeObject- the object to which the validation is done
3523 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3524 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3525 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3526 boolean inTransaction) {
3527 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3528 .getCapabilityType(type, inTransaction);
3529 if (eitherCapTypeFound.isRight()) {
3530 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3531 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3532 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3533 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3534 resource.getName());
3535 BeEcompErrorManager.getInstance()
3536 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3538 log.debug("Trying to get capability type {} failed with error: {}", type,
3539 eitherCapTypeFound.right().value().name());
3540 ResponseFormat errorResponse = null;
3542 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3544 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3547 eitherResult = Either.right(errorResponse);
3548 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3550 return eitherResult;
3553 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3554 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3555 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3556 boolean inTransaction) {
3557 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3558 .getCapabilityType(typeEntry.getKey(), inTransaction);
3559 if (eitherCapTypeFound.isRight()) {
3560 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3561 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3562 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3563 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3564 typeEntry.getKey(), resource.getName());
3565 BeEcompErrorManager.getInstance()
3566 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3568 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3569 eitherCapTypeFound.right().value().name());
3570 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3571 typeEntry.getKey());
3572 eitherResult = Either.right(errorResponse);
3573 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3575 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3576 if (capabilityTypeDefinition.getProperties() != null) {
3577 for (CapabilityDefinition capDef : typeEntry.getValue()) {
3578 List<ComponentInstanceProperty> properties = capDef.getProperties();
3579 if (properties == null || properties.isEmpty()) {
3580 properties = new ArrayList<>();
3581 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3582 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3583 properties.add(newProp);
3586 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3587 PropertyDefinition porpFromDef = prop.getValue();
3588 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3589 for (ComponentInstanceProperty cip : properties) {
3590 if (!cip.getName().equals(porpFromDef.getName())) {
3591 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3592 propsToAdd.add(newProp);
3595 if (!propsToAdd.isEmpty()) {
3596 properties.addAll(propsToAdd);
3600 capDef.setProperties(properties);
3603 return eitherResult;
3606 public Resource createResourceByDao(Resource resource, User user,
3607 AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3610 // lock new resource name in order to avoid creation resource with same
3612 Resource createdResource = null;
3613 if (!inTransaction) {
3614 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3616 if (lockResult.isRight()) {
3617 ResponseFormat responseFormat = lockResult.right().value();
3618 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3619 throw new ComponentException(responseFormat);
3622 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3625 if (resource.deriveFromGeneric()) {
3626 handleResourceGenericType(resource);
3628 createdResource = createResourceTransaction(resource, user, isNormative
3630 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3631 createdResource, actionEnum);
3632 ASDCKpiApi.countCreatedResourcesKPI();
3633 } catch(ComponentException e) {
3634 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
3635 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3637 } catch (StorageException e){
3638 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3639 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3643 if (!inTransaction) {
3644 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3645 NodeTypeEnum.Resource);
3648 return createdResource;
3651 private Resource createResourceTransaction(Resource resource, User user,
3652 boolean isNormative) {
3653 // validate resource name uniqueness
3654 log.debug("validate resource name");
3655 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3656 resource.getName(), resource.getResourceType(), resource.getComponentType());
3657 if (eitherValidation.isRight()) {
3658 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3659 eitherValidation.right().value());
3660 ResponseFormat errorResponse = componentsUtils
3661 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3662 throw new ComponentException(errorResponse);
3664 if (eitherValidation.left().value()) {
3665 log.debug("resource with name: {}, already exists", resource.getName());
3666 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3667 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3668 throw new ComponentException(errorResponse);
3671 log.debug("send resource {} to dao for create", resource.getName());
3673 createArtifactsPlaceHolderData(resource, user);
3676 log.debug("enrich resource with creator, version and state");
3677 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3678 resource.setVersion(INITIAL_VERSION);
3679 resource.setHighestVersion(true);
3680 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3681 resource.setAbstract(false);
3684 return toscaOperationFacade.createToscaComponent(resource)
3686 .on(r->throwComponentExceptionByResource(r, resource));
3689 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3690 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3691 componentsUtils.convertFromStorageResponse(status), resource);
3692 throw new ComponentException(responseFormat);
3695 private void createArtifactsPlaceHolderData(Resource resource, User user) {
3696 // create mandatory artifacts
3698 // TODO it must be removed after that artifact uniqueId creation will be
3699 // moved to ArtifactOperation
3701 setInformationalArtifactsPlaceHolder(resource, user);
3702 setDeploymentArtifactsPlaceHolder(resource, user);
3703 setToscaArtifactsPlaceHolders(resource, user);
3706 @SuppressWarnings("unchecked")
3708 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3709 Resource resource = (Resource) component;
3710 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3711 if (artifactMap == null) {
3712 artifactMap = new HashMap<>();
3714 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3715 .getConfiguration().getDeploymentResourceArtifacts();
3716 if (deploymentResourceArtifacts != null) {
3717 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3718 deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3720 resource.setDeploymentArtifacts(artifactMap);
3723 private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3724 boolean shouldCreateArtifact = true;
3725 Map<String, Object> artifactDetails = (Map<String, Object>) v;
3726 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3727 if (object != null) {
3728 List<String> artifactTypes = (List<String>) object;
3729 if (!artifactTypes.contains(resource.getResourceType().name())) {
3730 shouldCreateArtifact = false;
3734 log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3737 if (shouldCreateArtifact) {
3738 if (artifactsBusinessLogic != null) {
3739 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3740 resource.getUniqueId(), k, (Map<String, Object>) v,
3741 user, ArtifactGroupTypeEnum.DEPLOYMENT);
3742 if (artifactDefinition != null
3743 && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3744 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3750 @SuppressWarnings("unchecked")
3751 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3752 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3753 if (artifactMap == null) {
3754 artifactMap = new HashMap<>();
3756 String resourceUniqueId = resource.getUniqueId();
3757 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3758 .getExcludeResourceCategory();
3759 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3760 .getExcludeResourceType();
3761 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3762 .getConfiguration().getInformationalResourceArtifacts();
3763 List<CategoryDefinition> categories = resource.getCategories();
3764 boolean isCreateArtifact = true;
3765 if (exludeResourceCategory != null) {
3766 String category = categories.get(0).getName();
3767 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3769 if (isCreateArtifact && exludeResourceType != null) {
3770 String resourceType = resource.getResourceType().name();
3771 isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3773 if (informationalResourceArtifacts != null && isCreateArtifact) {
3774 Set<String> keys = informationalResourceArtifacts.keySet();
3775 for (String informationalResourceArtifactName : keys) {
3776 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3777 .get(informationalResourceArtifactName);
3778 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3779 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3780 ArtifactGroupTypeEnum.INFORMATIONAL);
3781 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3785 resource.setArtifacts(artifactMap);
3795 public ResponseFormat deleteResource(String resourceId, User user) {
3796 ResponseFormat responseFormat;
3797 validateUserExists(user, DELETE_RESOURCE, false);
3799 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3800 if (resourceStatus.isRight()) {
3801 log.debug("failed to get resource {}", resourceId);
3802 return componentsUtils
3803 .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3806 Resource resource = resourceStatus.left().value();
3808 StorageOperationStatus result = StorageOperationStatus.OK;
3809 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3810 if (lockResult.isRight()) {
3811 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3816 result = markComponentToDelete(resource);
3817 if (result.equals(StorageOperationStatus.OK)) {
3818 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3820 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3821 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3823 return responseFormat;
3826 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3827 titanDao.rollback();
3831 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3836 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3837 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3838 validateUserExists(user, DELETE_RESOURCE, false);
3839 Resource resource = null;
3840 StorageOperationStatus result = StorageOperationStatus.OK;
3843 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3844 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3845 if (resourceStatus.isRight()) {
3846 log.debug("failed to get resource {} version {}", resourceName, version);
3847 return componentsUtils.getResponseFormatByResource(
3848 componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3851 resource = resourceStatus.left().value();
3854 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3855 titanDao.rollback();
3856 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3857 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3862 if (resource != null) {
3863 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3865 if (lockResult.isRight()) {
3866 result = StorageOperationStatus.GENERAL_ERROR;
3867 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3870 result = markComponentToDelete(resource);
3871 if (!result.equals(StorageOperationStatus.OK)) {
3872 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3873 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3874 return responseFormat;
3878 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3879 titanDao.rollback();
3883 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3886 return responseFormat;
3889 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3892 validateUserExists(user, CREATE_RESOURCE, false);
3895 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3896 if (storageStatus.isRight()) {
3897 log.debug("failed to get resource by id {}", resourceId);
3898 return Either.right(componentsUtils.getResponseFormatByResource(
3899 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3901 if (!(storageStatus.left().value() instanceof Resource)) {
3902 return Either.right(componentsUtils.getResponseFormatByResource(
3903 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
3905 return Either.left(storageStatus.left().value());
3909 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
3912 validateUserExists(userId, "get Resource By Name And Version", false);
3914 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
3915 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
3916 if (getResource.isRight()) {
3917 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
3918 return Either.right(componentsUtils.getResponseFormatByResource(
3919 componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
3921 return Either.left(getResource.left().value());
3925 * updateResourceMetadata
3927 * @param user - modifier data (userId)
3928 * @param inTransaction TODO
3929 * @param resourceIdToUpdate - the resource identifier
3930 * @param newResource
3931 * @return Either<Resource , responseFormat>
3933 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
3934 Resource currentResource, User user, boolean inTransaction) {
3936 validateUserExists(user.getUserId(), "update Resource Metadata", false);
3938 log.debug("Get resource with id {}", resourceIdToUpdate);
3939 boolean needToUnlock = false;
3940 boolean rollbackNeeded = true;
3943 if (currentResource == null) {
3944 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
3945 .getToscaElement(resourceIdToUpdate);
3946 if (storageStatus.isRight()) {
3947 throw new ComponentException(componentsUtils.getResponseFormatByResource(
3948 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
3951 currentResource = storageStatus.left().value();
3953 // verify that resource is checked-out and the user is the last
3955 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
3956 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3960 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
3961 NodeTypeEnum.Resource);
3962 if (!lockResult.equals(StorageOperationStatus.OK)) {
3963 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
3964 NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
3965 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
3966 ResponseFormat responseFormat = componentsUtils
3967 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
3968 throw new ComponentException(responseFormat);
3971 needToUnlock = true;
3973 // critical section starts here
3974 // convert json to object
3976 // Update and updated resource must have a non-empty "derivedFrom"
3978 // This code is not called from import resources, because of root
3979 // VF "derivedFrom" should be null (or ignored)
3980 if (ModelConverter.isAtomicComponent(currentResource)) {
3981 validateDerivedFromNotEmpty(null, newResource, null);
3982 validateDerivedFromNotEmpty(null, currentResource, null);
3984 newResource.setDerivedFrom(null);
3987 Either<Boolean, ResponseFormat> validateAndUpdateInterfacesEither =
3988 interfaceOperationBusinessLogic.validateComponentNameAndUpdateInterfaces(currentResource, newResource);
3989 if (validateAndUpdateInterfacesEither.isRight()) {
3990 log.error("failed to validate and update Interfaces");
3991 rollbackNeeded = true;
3992 throw new ComponentException(validateAndUpdateInterfacesEither.right().value());
3995 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
3996 user, currentResource, false, true);
3997 if (dataModelResponse.isRight()) {
3998 log.debug("failed to update resource metadata!!!");
3999 rollbackNeeded = true;
4000 throw new ComponentException(dataModelResponse.right().value());
4003 log.debug("Resource metadata updated successfully!!!");
4004 rollbackNeeded = false;
4005 return dataModelResponse.left().value();
4007 } catch (ComponentException|StorageException e){
4008 rollback(inTransaction, newResource, null, null);
4012 if (!inTransaction) {
4016 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4021 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4022 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4023 updateVfModuleGroupsNames(currentResource, newResource);
4024 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4025 // Setting last updater and uniqueId
4026 newResource.setContactId(newResource.getContactId().toLowerCase());
4027 newResource.setLastUpdaterUserId(user.getUserId());
4028 newResource.setUniqueId(resourceIdToUpdate);
4029 // Cannot set highest version through UI
4030 newResource.setHighestVersion(currentResource.isHighestVersion());
4031 newResource.setCreationDate(currentResource.getCreationDate());
4033 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4034 newResource, user.getUserId(), inTransaction);
4036 if (processUpdateOfDerivedFrom.isRight()) {
4037 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4038 return Either.right(processUpdateOfDerivedFrom.right().value());
4041 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4042 if (isNotEmpty(newResource.getGroups())) {
4043 for (GroupDefinition group : newResource.getGroups()) {
4044 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4045 groupBusinessLogic.validateAndUpdateGroupMetadata(
4046 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4047 user, newResource.getComponentType(), group, true, false);
4051 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4052 .updateToscaElement(newResource);
4054 if (dataModelResponse.isRight()) {
4055 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4056 componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4057 return Either.right(responseFormat);
4058 } else if (dataModelResponse.left().value() == null) {
4059 log.debug("No response from updateResource");
4060 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4062 return Either.left(dataModelResponse.left().value());
4066 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4067 if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4068 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4070 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4072 newResource.setGroups(updatedGroups);
4076 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4077 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4078 if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4079 String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4080 String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4081 updatedGroup.setName(newGroupName);
4083 return updatedGroup;
4086 * validateResourceFieldsBeforeCreate
4088 * @param user - modifier data (userId)
4089 * @return Either<Boolean , ErrorResponse>
4091 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4092 AuditingActionEnum actionEnum, boolean inTransaction) {
4093 validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4094 // validate category
4095 log.debug("validate category");
4096 validateCategory(user, resource, actionEnum, inTransaction);
4097 // validate vendor name & release & model number
4098 log.debug("validate vendor name");
4099 validateVendorName(user, resource, actionEnum);
4100 log.debug("validate vendor release");
4101 validateVendorReleaseName(user, resource, actionEnum);
4102 log.debug("validate resource vendor model number");
4103 validateResourceVendorModelNumber(user, resource, actionEnum);
4105 log.debug("validate cost");
4106 validateCost(resource);
4107 // validate licenseType
4108 log.debug("validate licenseType");
4109 validateLicenseType(user, resource, actionEnum);
4110 // validate template (derived from)
4111 log.debug("validate derived from");
4112 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4113 resource.setDerivedFrom(null);
4115 validateDerivedFromExist(user, resource, actionEnum);
4116 // warn about non-updatable fields
4117 checkComponentFieldsForOverrideAttempt(resource);
4118 String currentCreatorFullName = resource.getCreatorFullName();
4119 if (currentCreatorFullName != null) {
4120 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4123 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4124 if (currentLastUpdaterFullName != null) {
4125 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4128 Long currentLastUpdateDate = resource.getLastUpdateDate();
4129 if (currentLastUpdateDate != null) {
4130 log.debug("Resource last update date is automatically set and cannot be updated");
4133 Boolean currentAbstract = resource.isAbstract();
4134 if (currentAbstract != null) {
4135 log.debug("Resource abstract is automatically set and cannot be updated");
4138 return Either.left(true);
4142 * validateResourceFieldsBeforeUpdate
4144 * @param currentResource - Resource object to validate
4147 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4148 boolean inTransaction, boolean isNested) {
4149 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4150 warnNonEditableFields(currentResource, updateInfoResource);
4153 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4154 String currentResourceVersion = currentResource.getVersion();
4155 String updatedResourceVersion = updateInfoResource.getVersion();
4157 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4158 log.debug("Resource version is automatically set and cannot be updated");
4161 String currentCreatorUserId = currentResource.getCreatorUserId();
4162 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4164 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4165 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4168 String currentCreatorFullName = currentResource.getCreatorFullName();
4169 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4171 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4172 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4175 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4176 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4178 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4179 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4182 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4183 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4185 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4186 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4189 Long currentCreationDate = currentResource.getCreationDate();
4190 Long updatedCreationDate = updateInfoResource.getCreationDate();
4192 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4193 log.debug("Resource Creation date is automatically set and cannot be updated");
4196 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4197 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4199 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4200 log.debug("Resource last update date is automatically set and cannot be updated");
4203 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4204 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4206 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4207 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4210 Boolean currentAbstract = currentResource.isAbstract();
4211 Boolean updatedAbstract = updateInfoResource.isAbstract();
4213 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4214 log.debug("Resource abstract is automatically set and cannot be updated");
4217 Boolean currentHighestVersion = currentResource.isHighestVersion();
4218 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4220 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4221 log.debug("Resource highest version is automatically set and cannot be updated");
4224 String currentUuid = currentResource.getUUID();
4225 String updatedUuid = updateInfoResource.getUUID();
4227 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4228 log.debug("Resource UUID is automatically set and cannot be updated");
4231 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4232 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4234 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4235 log.debug("Resource Type cannot be updated");
4238 updateInfoResource.setResourceType(currentResource.getResourceType());
4240 String currentInvariantUuid = currentResource.getInvariantUUID();
4241 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4243 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4244 log.debug("Resource invariant UUID is automatically set and cannot be updated");
4245 updateInfoResource.setInvariantUUID(currentInvariantUuid);
4249 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4250 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4251 log.debug("validate resource name before update");
4252 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4253 log.debug("validate description before update");
4254 validateDescriptionAndCleanup(null, updateInfoResource, null);
4255 log.debug("validate icon before update");
4256 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4257 log.debug("validate tags before update");
4258 validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4259 log.debug("validate vendor name before update");
4260 validateVendorName(null, updateInfoResource, null);
4261 log.debug("validate resource vendor model number before update");
4262 validateResourceVendorModelNumber(currentResource, updateInfoResource);
4263 log.debug("validate vendor release before update");
4264 validateVendorReleaseName(null, updateInfoResource, null);
4265 log.debug("validate contact info before update");
4266 validateContactId(null, updateInfoResource, null);
4267 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4268 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4269 log.debug("validate category before update");
4270 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4274 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4275 String resourceNameUpdated = updateInfoResource.getName();
4276 String resourceNameCurrent = currentResource.getName();
4277 if (resourceNameCurrent.equals(resourceNameUpdated)) {
4280 // In case of CVFC type we should support the case of old VF with CVFC
4281 // instances that were created without the "Cvfc" suffix
4282 return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4283 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4286 private String addCvfcSuffixToResourceName(String resourceName) {
4287 return resourceName + "Cvfc";
4290 private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4291 boolean hasBeenCertified, boolean isNested) {
4292 String resourceNameUpdated = updateInfoResource.getName();
4293 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4294 if (isNested || !hasBeenCertified) {
4295 validateComponentName(null, updateInfoResource, null);
4296 validateResourceNameUniqueness(updateInfoResource);
4297 currentResource.setName(resourceNameUpdated);
4298 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4299 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4302 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4303 resourceNameUpdated);
4304 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4309 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4310 String iconUpdated = updateInfoResource.getIcon();
4311 String iconCurrent = currentResource.getIcon();
4312 if (!iconCurrent.equals(iconUpdated)) {
4313 if (!hasBeenCertified) {
4314 validateIcon(null, updateInfoResource, null);
4316 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4317 throw new ComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4322 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4323 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4324 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4325 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4326 validateResourceVendorModelNumber(null, updateInfoResource, null);
4330 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4331 boolean hasBeenCertified, boolean inTransaction) {
4332 validateCategory(null, updateInfoResource, null, inTransaction);
4333 if (hasBeenCertified) {
4334 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4335 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4336 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4337 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4338 if (!currentCategory.getName().equals(updateCategory.getName())
4339 || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4340 log.info("Category {} cannot be updated once the resource has been certified once.",
4341 currentResource.getCategories());
4342 ResponseFormat errorResponse = componentsUtils
4343 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4344 return Either.right(errorResponse);
4347 return Either.left(true);
4350 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4351 Resource updateInfoResource, boolean hasBeenCertified) {
4353 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4354 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4355 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4356 || updatedDerivedFrom.isEmpty()) {
4357 log.trace("Update normative types");
4358 return Either.left(true);
4361 String derivedFromCurrent = currentDerivedFrom.get(0);
4362 String derivedFromUpdated = updatedDerivedFrom.get(0);
4364 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4365 if (!hasBeenCertified) {
4366 validateDerivedFromExist(null, updateInfoResource, null);
4368 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4369 currentResource, updateInfoResource, null);
4371 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4372 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4373 return validateDerivedFromExtending;
4377 // For derived from, we must know whether it was actually changed,
4378 // otherwise we must do no action.
4379 // Due to changes it inflicts on data model (remove artifacts,
4380 // properties...), it's not like a flat field which can be
4381 // overwritten if not changed.
4382 // So we must indicate that derived from is not changed
4383 updateInfoResource.setDerivedFrom(null);
4385 return Either.left(true);
4388 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4389 Resource updateInfoResource, boolean hasBeenCertified) {
4391 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4392 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4393 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4394 || updatedDerivedFrom.isEmpty()) {
4395 log.trace("Update normative types");
4396 return Either.left(true);
4399 String derivedFromCurrent = currentDerivedFrom.get(0);
4400 String derivedFromUpdated = updatedDerivedFrom.get(0);
4402 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4403 if (!hasBeenCertified) {
4404 validateDerivedFromExist(null, updateInfoResource, null);
4406 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4407 currentResource, updateInfoResource, null);
4409 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4410 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4411 return validateDerivedFromExtending;
4415 return Either.left(true);
4418 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
4419 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4422 String templateName = resource.getDerivedFrom().get(0);
4423 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4424 .validateToscaResourceNameExists(templateName);
4425 if (dataModelResponse.isRight()) {
4426 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4427 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4428 log.debug("request to data model failed with error: {}", storageStatus);
4429 ResponseFormat responseFormat = componentsUtils
4430 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4431 log.trace("audit before sending response");
4432 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4433 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4434 } else if (!dataModelResponse.left().value()) {
4435 log.info("resource template with name: {}, does not exists", templateName);
4436 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4437 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4438 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4442 // Tal G for extending inheritance US815447
4443 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4444 Resource updateInfoResource, AuditingActionEnum actionEnum) {
4445 String currentTemplateName = currentResource.getDerivedFrom().get(0);
4446 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4448 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4449 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4450 if (dataModelResponse.isRight()) {
4451 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4452 BeEcompErrorManager.getInstance()
4453 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4454 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4455 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4456 log.trace("audit before sending response");
4457 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4458 return Either.right(responseFormat);
4461 if (!dataModelResponse.left().value()) {
4462 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4463 currentTemplateName);
4464 ResponseFormat responseFormat = componentsUtils
4465 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4466 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4468 return Either.right(responseFormat);
4471 return Either.left(true);
4474 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4475 log.debug("validate resource derivedFrom field");
4476 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4477 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4478 log.info("derived from (template) field is missing for the resource");
4479 ResponseFormat responseFormat = componentsUtils
4480 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4481 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4483 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4487 private void validateResourceNameUniqueness(Resource resource) {
4489 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4490 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4491 resource.getComponentType());
4492 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4493 log.debug("resource with name: {}, already exists", resource.getName());
4494 throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4495 resource.getName());
4496 } else if(resourceOperationResponse.isRight()){
4497 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4498 throw new StorageException(resourceOperationResponse.right().value());
4503 private void validateCategory(User user, Resource resource,
4504 AuditingActionEnum actionEnum, boolean inTransaction) {
4506 List<CategoryDefinition> categories = resource.getCategories();
4507 if (CollectionUtils.isEmpty(categories)) {
4508 log.debug(CATEGORY_IS_EMPTY);
4509 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4510 ComponentTypeEnum.RESOURCE.getValue());
4511 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4512 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4513 ComponentTypeEnum.RESOURCE.getValue());
4515 if (categories.size() > 1) {
4516 log.debug("Must be only one category for resource");
4517 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4519 CategoryDefinition category = categories.get(0);
4520 List<SubCategoryDefinition> subcategories = category.getSubcategories();
4521 if (CollectionUtils.isEmpty(subcategories)) {
4522 log.debug("Missinig subcategory for resource");
4523 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4525 if (subcategories.size() > 1) {
4526 log.debug("Must be only one sub category for resource");
4527 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4530 SubCategoryDefinition subcategory = subcategories.get(0);
4532 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4533 log.debug(CATEGORY_IS_EMPTY);
4534 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4535 ComponentTypeEnum.RESOURCE.getValue());
4536 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4537 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4538 ComponentTypeEnum.RESOURCE.getValue());
4540 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4541 log.debug(CATEGORY_IS_EMPTY);
4542 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4543 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4544 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4545 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4548 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4551 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4552 User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4553 ResponseFormat responseFormat;
4554 if (category != null && subcategory != null) {
4555 log.debug("validating resource category {} against valid categories list", category);
4556 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4557 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4558 if (categories.isRight()) {
4559 log.debug("failed to retrive resource categories from Titan");
4560 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4561 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4562 throw new ComponentException(categories.right().value());
4564 List<CategoryDefinition> categoryList = categories.left().value();
4565 Optional<CategoryDefinition> foundCategory = categoryList.stream()
4566 .filter(cat -> cat.getName().equals(category.getName()))
4568 if(!foundCategory.isPresent()){
4569 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4570 category, categoryList);
4571 failOnInvalidCategory(user, resource, actionEnum);
4573 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4576 .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4578 if(!foundSubcategory.isPresent()){
4579 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4580 subcategory, foundCategory.get().getSubcategories());
4581 failOnInvalidCategory(user, resource, actionEnum);
4586 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4587 ResponseFormat responseFormat;
4588 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4589 ComponentTypeEnum.RESOURCE.getValue());
4590 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4591 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4592 ComponentTypeEnum.RESOURCE.getValue());
4595 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4596 String vendorRelease = resource.getVendorRelease();
4597 log.debug("validate vendor relese name");
4598 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4599 log.info("vendor relese name is missing.");
4600 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4601 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4602 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4605 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4608 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4609 if (vendorRelease != null) {
4610 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4611 log.info("vendor release exceds limit.");
4612 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4613 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4614 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4615 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4618 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4619 log.info("vendor release is not valid.");
4620 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4621 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4622 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4627 private void validateVendorName(User user, Resource resource,
4628 AuditingActionEnum actionEnum) {
4629 String vendorName = resource.getVendorName();
4630 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4631 log.info("vendor name is missing.");
4632 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4633 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4634 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
4636 validateVendorName(vendorName, user, resource, actionEnum);
4639 private void validateVendorName(String vendorName, User user, Resource resource,
4640 AuditingActionEnum actionEnum) {
4641 if (vendorName != null) {
4642 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4643 log.info("vendor name exceds limit.");
4644 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4645 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4646 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4647 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4648 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4651 if (!ValidationUtils.validateVendorName(vendorName)) {
4652 log.info("vendor name is not valid.");
4653 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4654 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4655 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
4660 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4661 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4662 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4663 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4664 log.info("resource vendor model number exceeds limit.");
4665 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4666 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4667 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4668 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4669 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4670 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4672 // resource vendor model number is currently validated as vendor
4674 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4675 log.info("resource vendor model number is not valid.");
4676 ResponseFormat errorResponse = componentsUtils
4677 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4678 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4679 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4685 private void validateCost(Resource resource) {
4686 String cost = resource.getCost();
4688 if (!ValidationUtils.validateCost(cost)) {
4689 log.debug("resource cost is invalid.");
4690 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4695 private void validateLicenseType(User user, Resource resource,
4696 AuditingActionEnum actionEnum) {
4697 log.debug("validate licenseType");
4698 String licenseType = resource.getLicenseType();
4699 if (licenseType != null) {
4700 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4702 if (!licenseTypes.contains(licenseType)) {
4703 log.debug("License type {} isn't configured", licenseType);
4704 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4705 if (actionEnum != null) {
4706 // In update case, no audit is required
4707 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4709 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4714 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4715 Resource updatedResource, String userId, boolean inTransaction) {
4716 Either<Operation, ResponseFormat> deleteArtifactByInterface;
4717 if (updatedResource.getDerivedFrom() != null) {
4718 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4719 log.debug("1. Removing interface artifacts from graph");
4720 // Remove all interface artifacts of resource
4721 String resourceId = updatedResource.getUniqueId();
4722 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4724 if (interfaces != null) {
4725 Collection<InterfaceDefinition> values = interfaces.values();
4726 for (InterfaceDefinition interfaceDefinition : values) {
4727 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4729 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4730 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4731 if (operations != null) {
4732 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4733 Operation operation = operationEntry.getValue();
4734 ArtifactDefinition implementation = operation.getImplementationArtifact();
4735 if (implementation != null) {
4736 String uniqueId = implementation.getUniqueId();
4737 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4738 uniqueId, operationEntry.getKey(), interfaceType);
4739 // only thing that transacts and locks here
4740 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4743 if (deleteArtifactByInterface.isRight()) {
4744 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4745 if (!inTransaction) {
4746 titanDao.rollback();
4748 return Either.right(deleteArtifactByInterface.right().value());
4751 log.trace("No implementation found for operation {} - nothing to delete",
4752 operationEntry.getKey());
4756 log.trace("No operations found for interface type {}", interfaceType);
4760 log.debug("2. Removing properties");
4761 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4762 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4764 if (findPropertiesOfNode.isRight()
4765 && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4766 log.debug("Failed to remove all properties of resource");
4767 if (!inTransaction) {
4768 titanDao.rollback();
4770 return Either.right(componentsUtils.getResponseFormat(
4771 componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4775 log.debug("Derived from wasn't changed during update");
4778 if (inTransaction) {
4779 return Either.left(true);
4782 return Either.left(true);
4786 /**** Auditing *******************/
4788 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4789 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4790 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4792 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4794 return webApplicationContext.getBean(class1);
4797 public ICapabilityTypeOperation getCapabilityTypeOperation() {
4798 return capabilityTypeOperation;
4801 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4802 this.capabilityTypeOperation = capabilityTypeOperation;
4805 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4806 log.debug("validate resource properties default values");
4807 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4808 List<PropertyDefinition> properties = resource.getProperties();
4809 if (properties != null) {
4810 eitherResult = iterateOverProperties(properties);
4812 return eitherResult;
4815 public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4816 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4818 String innerType = null;
4819 for (PropertyDefinition property : properties) {
4820 if (!propertyOperation.isPropertyTypeValid(property)) {
4821 log.info("Invalid type for property {}", property);
4822 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4823 ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4824 eitherResult = Either.right(responseFormat);
4828 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4829 applicationDataTypeCache);
4830 if (allDataTypes.isRight()) {
4831 return Either.right(allDataTypes.right().value());
4834 type = property.getType();
4836 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4837 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4838 if(responseFormat != null) {
4842 eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4844 return eitherResult;
4847 private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4848 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4849 log.info("Invalid default value for property {}", property);
4850 ResponseFormat responseFormat;
4851 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4852 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4853 property.getName(), type, innerType, property.getDefaultValue());
4855 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4856 property.getName(), type, property.getDefaultValue());
4858 return Either.right(responseFormat);
4861 return Either.left(true);
4864 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4865 ResponseFormat responseFormat = null;
4866 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4867 .isPropertyInnerTypeValid(property, allDataTypes);
4868 innerType = propertyInnerTypeValid.getLeft();
4869 if (!propertyInnerTypeValid.getRight().booleanValue()) {
4870 log.info("Invalid inner type for property {}", property);
4871 responseFormat = componentsUtils.getResponseFormat(
4872 ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4874 return responseFormat;
4878 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4879 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4883 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4884 return componentInstanceBusinessLogic;
4887 private String getComponentTypeForResponse(Component component) {
4888 String componentTypeForResponse = "SERVICE";
4889 if (component instanceof Resource) {
4890 componentTypeForResponse = ((Resource) component).getResourceType().name();
4892 return componentTypeForResponse;
4895 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4898 validateUserExists(user, "Get resource from csar UUID",
4901 // get resource from csar uuid
4902 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4903 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4904 if (either.isRight()) {
4905 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4907 return Either.right(resp);
4910 return Either.left(either.left().value());
4914 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
4915 String componentId, String userId) {
4919 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
4920 String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
4921 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4923 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
4924 uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
4925 return validCapabilitiesMap;
4928 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
4929 String capabilityType = capabilities.get(0).getType();
4930 if (defaultCapabilities.containsKey(capabilityType)) {
4931 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
4932 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
4933 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
4934 validCapabilityList.add(defaultCapability);
4935 validCapabilitiesMap.put(key, validCapabilityList);
4937 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
4941 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
4942 if (CollectionUtils.isEmpty(defaultCapability.getProperties())
4943 && isNotEmpty(capabilities.get(0).getProperties())) {
4944 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
4945 defaultCapability.getName(), resourceId);
4947 "Failed to update capability property values. Property list of fetched capability {} is empty. ",
4948 defaultCapability.getName());
4949 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
4950 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
4951 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
4955 private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
4956 CapabilityDefinition defaultCapability;
4957 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
4958 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
4960 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
4961 .getToscaFullElement(resourceId);
4962 if (getFullComponentRes.isRight()) {
4963 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
4964 getFullComponentRes.right().value());
4965 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
4968 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
4970 return defaultCapability;
4973 private void validateUniquenessUpdateUploadedComponentInstanceCapability(
4974 CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
4975 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
4976 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
4977 .collect(toMap(PropertyDefinition::getName, Function.identity()));
4978 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
4979 for (UploadPropInfo property : uploadedProperties) {
4980 String propertyName = property.getName().toLowerCase();
4981 String propertyType = property.getType();
4982 ComponentInstanceProperty validProperty;
4983 if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
4984 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
4987 validProperty = new ComponentInstanceProperty();
4988 validProperty.setName(propertyName);
4989 if (property.getValue() != null) {
4990 validProperty.setValue(property.getValue().toString());
4992 validProperty.setDescription(property.getDescription());
4993 validProperty.setPassword(property.isPassword());
4994 validProperties.add(validProperty);
4996 defaultCapability.setProperties(validProperties);
4999 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
5000 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
5003 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5004 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5005 Resource resource, User user) {
5007 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5008 ArtifactOperationEnum.class);
5009 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5010 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5011 .left(nodeTypeArtifactsToHandle);
5013 // add all found Csar artifacts to list to upload
5014 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5015 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5016 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5017 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5018 ArtifactDefinition foundArtifact;
5020 if (!existingArtifactsToHandle.isEmpty()) {
5021 foundArtifact = existingArtifactsToHandle.stream()
5022 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5024 if (foundArtifact != null) {
5025 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5026 .getArtifactType()) {
5027 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5028 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5029 // if current artifact already exists, but has
5030 // different content, add him to the list to
5032 artifactsToUpdate.add(currNewArtifact);
5034 // remove found artifact from the list of existing
5035 // artifacts to handle, because it was already
5037 existingArtifactsToHandle.remove(foundArtifact);
5038 // and remove found artifact from the list to
5039 // upload, because it should either be updated or be
5041 artifactsToUpload.remove(currNewArtifact);
5043 log.debug("Can't upload two artifact with the same name {}.",
5044 currNewArtifact.getArtifactName());
5045 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5046 ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5047 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5048 foundArtifact.getArtifactType());
5049 AuditingActionEnum auditingAction = artifactsBusinessLogic
5050 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5051 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5052 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5053 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5054 resource.getComponentType(), null);
5055 responseWrapper.setInnerElement(responseFormat);
5061 if (responseWrapper.isEmpty()) {
5062 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5063 if (currArtifact.getIsFromCsar()) {
5064 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5066 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5071 if (responseWrapper.isEmpty()) {
5072 if (!artifactsToUpload.isEmpty()) {
5073 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5075 if (!artifactsToUpdate.isEmpty()) {
5076 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5078 if (!artifactsToDelete.isEmpty()) {
5079 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5082 if (!responseWrapper.isEmpty()) {
5083 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5085 } catch (Exception e) {
5086 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5087 responseWrapper.setInnerElement(responseFormat);
5088 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5089 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5091 return nodeTypeArtifactsToHandleRes;
5094 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5095 String nodeTypeFullName) {
5097 String actualVfName;
5098 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5099 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5100 actualType = ResourceTypeEnum.VFC.name();
5102 actualVfName = vfResourceName;
5103 actualType = nodeResourceType;
5107 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
5108 String nameWithouNamespacePrefix = nodeTypeFullName
5109 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
5110 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5111 String resourceType = findTypes[0];
5112 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
5114 if (actualName.startsWith(Constants.ABSTRACT)) {
5115 toscaResourceName.append(resourceType.toLowerCase()).append('.')
5116 .append(ValidationUtils.convertToSystemName(actualVfName));
5118 toscaResourceName.append(actualType.toLowerCase()).append('.')
5119 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5121 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5122 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5123 previousToscaResourceName
5124 .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
5126 } catch (Exception e) {
5127 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
5128 log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
5129 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
5133 public ICacheMangerOperation getCacheManagerOperation() {
5134 return cacheManagerOperation;
5137 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
5138 this.cacheManagerOperation = cacheManagerOperation;
5142 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
5144 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5145 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
5148 if (resourceResultEither.isRight()) {
5149 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5150 log.debug("Failed to found resource with id {} ", resourceId);
5151 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5154 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5155 return Either.right(componentsUtils.getResponseFormatByResource(
5156 componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5159 Resource resource = resourceResultEither.left().value();
5160 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5161 dataParamsToReturn);
5162 return Either.left(dataTransfer);
5166 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5167 Resource resource = (Resource) clonedComponent;
5168 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5169 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5170 .shouldUpgradeToLatestDerived(resource);
5171 if (shouldUpgradeToLatestDerived.isRight()) {
5172 return Either.right(
5173 componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5175 return Either.left(shouldUpgradeToLatestDerived.left().value());
5177 return super.shouldUpgradeToLatestDerived(clonedComponent);