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.operations.InterfaceOperation;
67 import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
68 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
69 import org.openecomp.sdc.be.model.operations.StorageException;
70 import org.openecomp.sdc.be.model.operations.api.*;
71 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
72 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
73 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
74 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
75 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
76 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
77 import org.openecomp.sdc.be.tosca.CsarUtils;
78 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
79 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
80 import org.openecomp.sdc.be.user.IUserBusinessLogic;
81 import org.openecomp.sdc.be.user.UserBusinessLogic;
82 import org.openecomp.sdc.be.utils.CommonBeUtils;
83 import org.openecomp.sdc.be.utils.TypeUtils;
84 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
85 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
86 import org.openecomp.sdc.common.api.Constants;
87 import org.openecomp.sdc.common.datastructure.Wrapper;
88 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
89 import org.openecomp.sdc.common.log.wrappers.Logger;
90 import org.openecomp.sdc.common.util.GeneralUtility;
91 import org.openecomp.sdc.common.util.ValidationUtils;
92 import org.openecomp.sdc.exception.ResponseFormat;
93 import org.springframework.beans.factory.annotation.Autowired;
94 import org.springframework.web.context.WebApplicationContext;
95 import org.yaml.snakeyaml.DumperOptions;
96 import org.yaml.snakeyaml.Yaml;
98 import javax.servlet.ServletContext;
100 import java.util.Map.Entry;
101 import java.util.function.Function;
102 import java.util.regex.Pattern;
104 import static java.util.stream.Collectors.*;
105 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
106 import static org.apache.commons.collections.MapUtils.isEmpty;
107 import static org.apache.commons.collections.MapUtils.isNotEmpty;
108 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
109 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
110 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
112 @org.springframework.stereotype.Component("resourceBusinessLogic")
113 public class ResourceBusinessLogic extends ComponentBusinessLogic {
115 private static final String DELETE_RESOURCE = "Delete Resource";
116 private static final String IN_RESOURCE = " in resource {} ";
117 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
118 public static final String INITIAL_VERSION = "0.1";
119 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
120 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
121 private static final String CREATE_RESOURCE = "Create Resource";
122 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
123 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
124 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
125 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
126 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
129 * Default constructor
131 public ResourceBusinessLogic() {
132 log.debug("ResourceBusinessLogic started");
136 private ICapabilityTypeOperation capabilityTypeOperation = null;
139 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
142 private LifecycleBusinessLogic lifecycleBusinessLogic;
145 private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
148 private ResourceImportManager resourceImportManager;
151 private InputsBusinessLogic inputsBusinessLogic;
154 private CompositionBusinessLogic compositionBusinessLogic;
157 private ICacheMangerOperation cacheManagerOperation;
160 private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
163 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
166 private MergeInstanceUtils mergeInstanceUtils;
169 private UiComponentDataConverter uiComponentDataConverter;
172 private CsarBusinessLogic csarBusinessLogic;
175 private InterfaceOperation interfaceOperation;
177 public void setInterfaceOperation(InterfaceOperation interfaceOperation) {
178 this.interfaceOperation = interfaceOperation;
181 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
182 return lifecycleBusinessLogic;
185 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
186 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
189 public IElementOperation getElementDao() {
193 public void setElementDao(IElementOperation elementDao) {
194 this.elementDao = elementDao;
197 public IUserBusinessLogic getUserAdmin() {
198 return this.userAdmin;
201 public void setUserAdmin(UserBusinessLogic userAdmin) {
202 this.userAdmin = userAdmin;
205 public ComponentsUtils getComponentsUtils() {
206 return this.componentsUtils;
209 public void setComponentsUtils(ComponentsUtils componentsUtils) {
210 this.componentsUtils = componentsUtils;
213 public ArtifactsBusinessLogic getArtifactsManager() {
214 return artifactsBusinessLogic;
217 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
218 this.artifactsBusinessLogic = artifactsManager;
221 public ApplicationDataTypeCache getApplicationDataTypeCache() {
222 return applicationDataTypeCache;
225 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
226 this.applicationDataTypeCache = applicationDataTypeCache;
229 public void setInterfaceTypeOperation(IInterfaceLifecycleOperation interfaceTypeOperation) {
230 this.interfaceTypeOperation = interfaceTypeOperation;
234 * the method returns a list of all the resources that are certified, the
235 * returned resources are only abstract or only none abstract according to
242 public List<Resource> getAllCertifiedResources(boolean getAbstract,
243 HighestFilterEnum highestFilter, String userId) {
244 User user = validateUserExists(userId, "get All Certified Resources", false);
245 Boolean isHighest = null;
246 switch (highestFilter) {
252 case NON_HIGHEST_ONLY:
258 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
259 .getAllCertifiedResources(getAbstract, isHighest);
261 if (getResponse.isRight()) {
262 throw new StorageException(getResponse.right().value());
265 return getResponse.left().value();
268 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
269 ResourceTypeEnum resourceTypeEnum, String userId) {
271 validateUserExists(userId, "validate Resource Name Exists", false);
273 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
274 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
278 if (dataModelResponse.isLeft()) {
279 Map<String, Boolean> result = new HashMap<>();
280 result.put("isValid", dataModelResponse.left().value());
281 log.debug("validation was successfully performed.");
282 return Either.left(result);
285 ResponseFormat responseFormat = componentsUtils
286 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
288 return Either.right(responseFormat);
291 public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
292 User user, Map<String, byte[]> csarUIPayload, String payloadName) {
293 validateResourceBeforeCreate(resource, user, false);
294 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
295 if (StringUtils.isNotEmpty(csarUUID)) {
296 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
297 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
298 return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
301 return createResourceByDao(resource, user, auditingAction, false, false);
304 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
305 Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
306 String csarUUID = payloadName;
307 String csarVersion = null;
308 Resource updatedResource = null;
309 if (payloadName == null) {
310 csarUUID = resource.getCsarUUID();
311 csarVersion = resource.getCsarVersion();
313 if (csarUUID != null && !csarUUID.isEmpty()) {
314 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
315 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
316 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
317 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
318 overrideImmutableMetadata(oldResource, resource);
320 validateResourceBeforeCreate(resource, user, false);
321 String oldCsarVersion = oldResource.getCsarVersion();
322 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
324 // (on boarding flow): If the update includes same csarUUID and
325 // same csarVersion as already in the VF - no need to import the
326 // csar (do only metadata changes if there are).
327 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
328 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
331 updatedResource = updateResourceFromCsar(oldResource, resource, user,
332 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
335 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
336 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
338 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
339 throw new ComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
341 return updatedResource;
344 private void validateCsarIsNotAlreadyUsed(Resource oldResource,
345 Resource resource, String csarUUID, User user) {
346 // (on boarding flow): If the update includes a csarUUID: verify this
347 // csarUUID is not in use by another VF, If it is - use same error as
349 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
350 // select another or update the existing VF." %1 - csarUUID, %2 - VF
352 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
353 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
354 if (resourceLinkedToCsarRes.isRight()) {
355 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
356 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
357 resource.getSystemName());
358 throw new StorageException(resourceLinkedToCsarRes.right().value());
360 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
361 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
362 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
363 resourceLinkedToCsarRes.left().value().getName());
364 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
365 throw new ComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
366 resourceLinkedToCsarRes.left().value().getName());
370 private void validateCsarUuidMatching(Resource resource,
371 Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
372 // (on boarding flow): If the update includes csarUUID which is
373 // different from the csarUUID of the VF - fail with
374 // error: "Error: Resource %1 cannot be updated using since it is linked
375 // to a different VSP" %1 - VF name
376 String oldCsarUUID = oldResource.getCsarUUID();
377 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
379 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
380 resourceUniqueId, csarUUID, oldCsarUUID);
381 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
382 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
383 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
384 throw new ComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
388 private Resource getResourceByUniqueId(String resourceUniqueId) {
389 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
390 if (oldResourceRes.isRight()) {
391 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
392 oldResourceRes.right().value());
393 throw new StorageException(oldResourceRes.right().value());
395 return oldResourceRes.left().value();
398 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
399 resource.setName(oldRresource.getName());
400 resource.setIcon(oldRresource.getIcon());
401 resource.setTags(oldRresource.getTags());
402 resource.setCategories(oldRresource.getCategories());
403 resource.setDerivedFrom(oldRresource.getDerivedFrom());
406 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
407 User user, AuditingActionEnum updateResource, boolean inTransaction,
408 Map<String, byte[]> csarUIPayload, String csarUUID) {
409 Resource updatedResource = null;
410 validateLifecycleState(oldResource, user);
411 String lockedResourceId = oldResource.getUniqueId();
412 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
413 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
414 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
415 "update Resource From Csar");
416 if (lockResult.isRight()) {
417 throw new ComponentException(lockResult.right().value());
420 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
422 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
423 nodeTypesInfo, csarInfo, oldResource);
424 if (findNodeTypesArtifactsToHandleRes.isRight()) {
425 log.debug("failed to find node types for update with artifacts during import csar {}. ",
426 csarInfo.getCsarUUID());
427 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
429 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
432 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
433 csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
435 connectUiRelations(oldResource, updatedResource);
437 } catch (ComponentException|StorageException e){
438 rollback(inTransaction, newResource, createdArtifacts, null);
443 log.debug("unlock resource {}", lockedResourceId);
444 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
446 return updatedResource;
450 private void validateLifecycleState(Resource oldResource, User user) {
451 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
452 !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
453 log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
454 oldResource.getLastUpdaterUserId(), user.getUserId());
455 throw new ComponentException(ActionStatus.RESTRICTED_OPERATION);
459 private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
460 Either<Resource, ResponseFormat> result;
462 List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
464 StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
465 if (status == StorageOperationStatus.OK) {
466 newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
467 result = Either.left(newResource);
469 result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
475 private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
476 AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
477 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
478 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
479 String nodeName, boolean isNested) {
480 boolean inTransaction = true;
481 boolean shouldLock = false;
482 Resource preparedResource = null;
483 ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
485 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
486 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
487 preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
488 inTransaction, shouldLock, isNested).left;
489 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
490 handleResourceGenericType(preparedResource);
491 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
492 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
493 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
494 preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
495 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
496 } catch (ComponentException e) {
497 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
498 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
499 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
501 } catch (StorageException e){
502 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
503 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
504 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
507 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
508 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
509 preparedResource.getSystemName());
510 if (validateUpdateVfGroupNamesRes.isRight()) {
512 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
514 // add groups to resource
515 Map<String, GroupDefinition> groups;
517 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
518 groups = validateUpdateVfGroupNamesRes.left().value();
520 groups = uploadComponentInstanceInfoMap.getGroups();
522 handleGroupsProperties(preparedResource, groups);
523 preparedResource = updateGroupsOnResource(preparedResource, groups);
524 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
525 nodeTypesArtifactsToHandle);
527 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
528 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
529 if (updateArtifactsEither.isRight()) {
530 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
531 throw new ComponentException(updateArtifactsEither.right().value());
533 preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
535 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
536 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
537 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
539 throw new ComponentException(responseFormat);
541 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
542 return preparedResource;
545 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
546 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
547 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
549 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
550 Resource resource = preparedResource;
552 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
553 .getNodeTypesArtifactsToHandle();
554 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
555 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
556 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
557 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
558 if (handleNodeTypeArtifactsRes.isRight()) {
559 return Either.right(handleNodeTypeArtifactsRes.right().value());
563 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
564 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
565 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
566 if (createdCsarArtifactsEither.isRight()) {
567 return createdCsarArtifactsEither;
570 resource = createdCsarArtifactsEither.left().value();
572 return Either.left(resource);
575 private Resource handleResourceGenericType(Resource resource) {
576 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
577 if (resource.shouldGenerateInputs()) {
578 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
580 return genericResource;
583 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
584 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
586 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
587 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
588 = Either.left(nodeTypesArtifactsToHandle);
591 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
592 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
593 extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
594 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
595 oldResource.getName(), csarInfo.getCsarUUID());
596 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
597 extractedVfcsArtifacts,
598 namespace, vfcToscaNames));
599 } catch (Exception e) {
600 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
601 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
602 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
604 return nodeTypesArtifactsToHandleRes;
607 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
608 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
610 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
611 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
612 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
613 if (!isEmpty(extractedVfcsArtifacts)) {
614 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
615 if (extractedVfcsArtifacts.containsKey(namespace)) {
616 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
618 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
619 } else if (curNodeType != null) {
620 // delete all artifacts if have not received artifacts from
622 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
623 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
624 // delete all informational artifacts
625 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
626 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
628 // delete all deployment artifacts
629 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
630 if (!artifactsToDelete.isEmpty()) {
631 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
634 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
635 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
639 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
640 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
641 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
642 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
643 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
644 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
645 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
646 return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
648 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
653 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
654 Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
656 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
658 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
659 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
660 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
661 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
662 collectExistingArtifacts(curNodeType));
663 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
664 } catch (Exception e) {
665 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
666 throw new ComponentException(ActionStatus.GENERAL_ERROR);
668 return nodeTypeArtifactsToHandle;
671 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
672 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
673 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
674 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
675 if (!artifactsToUpload.isEmpty()) {
676 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
678 if (!artifactsToUpdate.isEmpty()) {
679 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
681 if (!artifactsToDelete.isEmpty()) {
682 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
685 return nodeTypeArtifactsToHandle;
688 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
689 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
690 Map<String, ArtifactDefinition> existingArtifacts) {
691 if (!existingArtifacts.isEmpty()) {
692 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
693 artifactsToDelete.addAll(existingArtifacts.values());
697 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
698 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
700 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
702 if (foundArtifact.isPresent()) {
703 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
704 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
705 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
706 artifactsToUpload.remove(currNewArtifact);
708 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
709 throw new ComponentException(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
710 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
711 foundArtifact.get().getArtifactType());
716 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
717 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
718 foundArtifact.setPayload(currNewArtifact.getPayloadData());
719 foundArtifact.setPayloadData(
720 Base64.encodeBase64String(currNewArtifact.getPayloadData()));
721 foundArtifact.setArtifactChecksum(GeneralUtility
722 .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
723 artifactsToUpdate.add(foundArtifact);
727 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
728 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
729 if (curNodeType == null) {
730 return existingArtifacts;
732 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
733 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
735 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
737 .putAll(curNodeType.getArtifacts().entrySet()
739 .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
740 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
742 return existingArtifacts;
746 * Changes resource life cycle state to checked out
750 * @param inTransaction
753 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
754 Either<Resource, ResponseFormat> checkoutResourceRes;
756 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
757 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
759 "************* Going to change life cycle state of resource {} to not certified checked out. ",
761 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
762 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
763 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
764 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
765 inTransaction, true);
766 if (checkoutRes.isRight()) {
767 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
768 resource.getComponentType().getNodeType(), resource.getUniqueId(),
769 checkoutRes.right().value().getStatus());
770 checkoutResourceRes = Either.right(checkoutRes.right().value());
772 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
775 checkoutResourceRes = Either.left(resource);
777 } catch (Exception e) {
778 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
779 checkoutResourceRes = Either.right(responseFormat);
780 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
783 return checkoutResourceRes;
787 * Handles Artifacts of NodeType
789 * @param nodeTypeResource
790 * @param nodeTypeArtifactsToHandle
792 * @param inTransaction
795 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
796 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
797 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
798 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
799 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
800 Either<Resource, ResponseFormat> changeStateResponse;
802 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
803 if (changeStateResponse.isRight()) {
804 return Either.right(changeStateResponse.right().value());
806 nodeTypeResource = changeStateResponse.left().value();
808 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
809 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
810 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
812 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
813 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
814 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
815 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
816 nodeTypeResource.getName());
817 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
818 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
819 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
820 ignoreLifecycleState, curOperation),
821 false, inTransaction);
822 if (handleNodeTypeArtifactsRequestRes.isRight()) {
823 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
826 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
827 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
829 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
832 if (handleNodeTypeArtifactsRes == null) {
833 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
835 } catch (Exception e) {
836 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
837 handleNodeTypeArtifactsRes = Either.right(responseFormat);
838 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
840 return handleNodeTypeArtifactsRes;
843 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
844 String vfResourceName, CsarInfo csarInfo) {
845 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
847 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
848 if (!nodes.isEmpty()) {
849 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
850 while (nodesNameEntry.hasNext()) {
851 Entry<String, Object> nodeType = nodesNameEntry.next();
852 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
853 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
854 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
857 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
858 vfcToscaNames.put(cvfc.getType(),
859 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
861 return vfcToscaNames;
864 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
865 Map<String, Object> nodes = new HashMap<>();
866 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
867 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
869 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
873 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
874 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
875 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
876 if (eitherNodeTypes.isLeft()) {
877 nodes.putAll(eitherNodeTypes.left().value());
881 public Resource createResourceFromCsar(Resource resource, User user,
882 Map<String, byte[]> csarUIPayload, String csarUUID) {
883 log.trace("************* created successfully from YAML, resource TOSCA ");
885 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
887 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
888 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
889 nodeTypesInfo, csarInfo, resource);
890 if (findNodeTypesArtifactsToHandleRes.isRight()) {
891 log.debug("failed to find node types for update with artifacts during import csar {}. ",
892 csarInfo.getCsarUUID());
893 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
895 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
896 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
898 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
899 vfResource.getToscaResourceName());
903 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
904 log.trace("validating resource before create");
905 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
906 // validate user role
907 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
908 // VF / PNF "derivedFrom" should be null (or ignored)
909 if (ModelConverter.isAtomicComponent(resource)) {
910 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
912 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
916 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
917 // nodeTypesArtifactsToCreate, true, false, null
918 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
919 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
920 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
921 boolean shouldLock, boolean inTransaction, String nodeName) {
923 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
924 Resource createdResource;
926 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
927 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
928 createdResource = createResourceAndRIsFromYaml(yamlName, resource,
929 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
930 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
931 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
932 } catch (ComponentException e) {
933 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
934 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
936 } catch (StorageException e){
937 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
938 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
941 return createdResource;
945 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
946 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
947 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
950 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
951 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
952 if (toscaVersion.isRight()) {
953 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
955 Map<String, Object> mapToConvert = new HashMap<>();
956 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
957 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
958 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
959 return csarInfo.getCreatedNodes();
962 private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
963 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
964 .left().orValue(HashMap::new);
967 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) {
968 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
969 Resource vfcCreated = null;
970 while (nodesNameValueIter.hasNext()) {
971 Entry<String, Object> nodeType = nodesNameValueIter.next();
972 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
973 || nodeTypesArtifactsToHandle.isEmpty() ? null
974 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
976 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
977 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
978 vfcCreated = handleNestedVfc(resource,
979 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
981 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
982 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
983 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
984 log.trace("************* Going to create node {}", nodeType.getKey());
985 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
986 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
988 log.debug("************* Finished to create node {}", nodeType.getKey());
990 vfcCreated = resourceCreated.getLeft();
991 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
992 vfcCreated.getToscaResourceName());
994 if (vfcCreated != null) {
995 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
997 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
1001 private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1002 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1005 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1006 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1008 log.debug("************* Going to create node types from yaml {}", yamlName);
1009 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
1010 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1011 log.debug("************* Finished to create node types from yaml {}", yamlName);
1013 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1014 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1015 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1016 csarInfo, nodeName, yamlName);
1021 private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1022 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1023 String nodeName, String yamlName) {
1025 Resource oldComplexVfc = null;
1026 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1027 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1028 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1029 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1030 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1031 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1032 nodeName).getRight());
1034 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1035 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1036 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1037 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1038 } else if (oldComplexVfcRes.isLeft()) {
1039 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1040 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1041 oldComplexVfcRes.left().value(), newComplexVfc,
1042 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1043 if (eitherValidation.isLeft()) {
1044 oldComplexVfc = oldComplexVfcRes.left().value();
1047 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1048 oldComplexVfc, newComplexVfc);
1049 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1050 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1051 CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1052 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1053 Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1055 if (result.isRight()) {
1056 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1058 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1059 csarInfo.removeNodeFromQueue();
1060 return result.left().value();
1063 private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1064 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1065 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1067 Resource handleComplexVfcRes;
1068 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1069 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1070 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1071 .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
1072 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1073 if (oldComplexVfc == null) {
1074 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1075 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1077 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1078 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1079 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1081 return handleComplexVfcRes;
1084 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1085 Map<String, NodeTypeInfo> nodesInfo) {
1087 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1088 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1089 csarInfo.addNodeToQueue(nodeName);
1090 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1091 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1094 private String getNodeTypeActualName(String fullName) {
1095 String nameWithouNamespacePrefix = fullName
1096 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1097 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1098 String resourceType = findTypes[0];
1099 return nameWithouNamespacePrefix.substring(resourceType.length());
1102 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1103 String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1104 Resource resourceVf, boolean needLock,
1105 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1106 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1109 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1111 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1112 resourceMetaData.getResourceType(), csarInfo);
1113 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1114 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1115 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1116 nodeNameValue.getKey(), isNested);
1119 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1120 String nodeResourceType, CsarInfo csarInfo) {
1121 // We need to create a Yaml from each node_types in order to create
1122 // resource from each node type using import normative flow.
1123 DumperOptions options = new DumperOptions();
1124 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1125 Yaml yaml = new Yaml(options);
1127 Map<String, Object> node = new HashMap<>();
1128 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1129 .getLeft(), nodeNameValue.getValue());
1130 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1132 return yaml.dumpAsMap(mapToConvert);
1135 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1136 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1137 return Either.left(true);
1140 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1141 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1142 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1143 String nodeName, boolean isNested) {
1145 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1146 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1147 Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1148 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1149 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1150 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
1151 .left().on(this::failOnCertification);
1154 private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
1155 throw new ComponentException(error);
1158 private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1159 String nodeName, User user) {
1160 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1162 // validate nodetype name prefix
1163 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1164 log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1165 Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1166 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1167 yamlName, resourceMetaData.getName(), nodeName);
1170 String actualName = this.getNodeTypeActualName(nodeName);
1171 String namePrefix = nodeName.replace(actualName, "");
1172 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1174 // if we import from csar, the node_type name can be
1175 // org.openecomp.resource.abstract.node_name - in this case we always
1177 if (resourceType.equals(Constants.ABSTRACT)) {
1178 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1181 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1182 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1183 ResourceTypeEnum.values());
1184 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1185 yamlName, resourceMetaData.getName(), nodeName);
1189 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1191 // Setting type from name
1192 String type = resourceType.toUpperCase();
1193 resourceMetaData.setResourceType(type);
1195 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1196 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1197 resourceMetaData.setContactId(user.getUserId());
1198 resourceMetaData.setVendorName(resourceVf.getVendorName());
1199 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1202 List<String> tags = new ArrayList<>();
1203 tags.add(resourceMetaData.getName());
1204 resourceMetaData.setTags(tags);
1207 CategoryDefinition category = new CategoryDefinition();
1208 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1209 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1210 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1211 category.addSubCategory(subCategory);
1212 List<CategoryDefinition> categories = new ArrayList<>();
1213 categories.add(category);
1214 resourceMetaData.setCategories(categories);
1216 return resourceMetaData;
1219 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1220 Map<String, NodeTypeInfo> nodesInfo) {
1221 Resource cvfc = new Resource();
1222 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1223 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1224 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1225 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1226 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1227 cvfc.setAbstract(true);
1228 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1229 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1230 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1231 cvfc.setContactId(csarInfo.getModifier().getUserId());
1232 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1233 cvfc.setVendorName(resourceVf.getVendorName());
1234 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1235 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1236 cvfc.setToscaResourceName(
1237 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1239 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1241 List<String> tags = new ArrayList<>();
1242 tags.add(cvfc.getName());
1245 CategoryDefinition category = new CategoryDefinition();
1246 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1247 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1248 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1249 category.addSubCategory(subCategory);
1250 List<CategoryDefinition> categories = new ArrayList<>();
1251 categories.add(category);
1252 cvfc.setCategories(categories);
1254 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1255 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1256 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1261 private String buildCvfcName(String resourceVfName, String nodeName) {
1262 String nameWithouNamespacePrefix = nodeName
1263 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1264 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1265 String resourceType = findTypes[0];
1266 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1267 return addCvfcSuffixToResourceName(resourceName);
1270 private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
1271 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1272 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1273 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1274 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1275 boolean shouldLock, boolean inTransaction, String nodeName) {
1277 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1280 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1282 if (lockResult.isRight()) {
1283 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1284 throw new ComponentException(lockResult.right().value());
1286 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1289 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1290 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1291 resource = createResourceTransaction(resource,
1292 csarInfo.getModifier(), isNormative);
1293 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1294 log.trace("************* Going to add inputs from yaml {}", yamlName);
1295 if (resource.shouldGenerateInputs())
1296 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1298 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1299 resource = createInputsOnResource(resource, inputs);
1300 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1302 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1304 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1306 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1307 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1308 nodeTypesArtifactsToCreate, nodeName);
1309 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1310 // validate update vf module group names
1311 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1312 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1313 if (validateUpdateVfGroupNamesRes.isRight()) {
1314 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1315 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
1317 // add groups to resource
1318 Map<String, GroupDefinition> groups;
1319 log.trace("************* Going to add groups from yaml {}", yamlName);
1321 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1322 groups = validateUpdateVfGroupNamesRes.left().value();
1324 groups = parsedToscaYamlInfo.getGroups();
1327 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1329 if (createGroupsOnResource.isRight()) {
1330 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1331 throw new ComponentException(createGroupsOnResource.right().value());
1333 resource = createGroupsOnResource.left().value();
1334 log.trace("************* Finished to add groups from yaml {}", yamlName);
1336 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1338 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1339 nodeTypesArtifactsToCreate);
1341 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1342 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1343 if (createArtifactsEither.isRight()) {
1344 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1345 throw new ComponentException(createArtifactsEither.right().value());
1348 resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
1350 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1351 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1352 ASDCKpiApi.countCreatedResourcesKPI();
1355 } catch(ComponentException|StorageException e) {
1356 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1359 if (!inTransaction) {
1363 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1364 NodeTypeEnum.Resource);
1369 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1370 if(!inTransaction) {
1371 titanDao.rollback();
1373 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1374 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1375 log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
1379 private Resource getResourceWithGroups(String resourceId) {
1381 ComponentParametersView filter = new ComponentParametersView();
1382 filter.setIgnoreGroups(false);
1383 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
1384 if (updatedResource.isRight()) {
1385 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
1387 return updatedResource.left().value();
1390 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1391 Map<String, GroupDefinition> groups) {
1392 if (groups != null && !groups.isEmpty()) {
1393 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
1395 handleGroupsProperties(resource, groups);
1396 fillGroupsFinalFields(groupsAsList);
1397 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1398 groupsAsList, true);
1399 if (createGroups.isRight()) {
1400 return Either.right(createGroups.right().value());
1403 return Either.left(resource);
1405 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1406 .getToscaElement(resource.getUniqueId());
1407 if (updatedResource.isRight()) {
1408 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1409 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1410 return Either.right(responseFormat);
1412 return Either.left(updatedResource.left().value());
1415 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1416 List<InputDefinition> inputs = resource.getInputs();
1417 if (MapUtils.isNotEmpty(groups)) {
1420 .filter(g -> isNotEmpty(g.getProperties()))
1421 .flatMap(g -> g.getProperties().stream())
1422 .forEach(p -> handleGetInputs(p, inputs));
1426 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1427 if (isNotEmpty(property.getGetInputValues())) {
1428 if (inputs == null || inputs.isEmpty()) {
1429 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1430 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1432 .map(GetInputValueDataDefinition::getInputName)
1433 .collect(toList()).toString());
1435 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1436 while (getInputValuesIter.hasNext()) {
1437 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1438 InputDefinition input = findInputByName(inputs, getInput);
1439 getInput.setInputId(input.getUniqueId());
1440 if (getInput.getGetInputIndex() != null) {
1441 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1442 input = findInputByName(inputs, getInputIndex);
1443 getInputIndex.setInputId(input.getUniqueId());
1444 getInputValuesIter.add(getInputIndex);
1450 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1451 Optional<InputDefinition> inputOpt = inputs.stream()
1452 .filter(p -> p.getName().equals(getInput.getInputName()))
1454 if (!inputOpt.isPresent()) {
1455 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1456 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1458 return inputOpt.get();
1461 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1462 groupsAsList.forEach(groupDefinition -> {
1463 groupDefinition.setInvariantName(groupDefinition.getName());
1464 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1468 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1469 if (isEmpty(groups)) {
1472 updateOrCreateGroups(resource, groups);
1474 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1475 .getToscaElement(resource.getUniqueId());
1476 if (updatedResource.isRight()) {
1477 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1478 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1480 return updatedResource.left().value();
1483 private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1484 List<GroupDefinition> groupsFromResource = resource.getGroups();
1485 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1486 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1487 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1488 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1489 if (isNotEmpty(groupsFromResource)) {
1490 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1491 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1493 groupsToCreate.addAll(groupsAsList);
1495 if (isNotEmpty(groupsToCreate)) {
1496 fillGroupsFinalFields(groupsToCreate);
1497 if (isNotEmpty(groupsFromResource)) {
1498 groupBusinessLogic.addGroups(resource,
1499 groupsToCreate, true)
1501 .on(this::throwComponentException);
1503 groupBusinessLogic.createGroups(resource,
1504 groupsToCreate, true)
1506 .on(this::throwComponentException);
1509 if (isNotEmpty(groupsToDelete)) {
1510 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1512 .on(this::throwComponentException);
1514 if (isNotEmpty(groupsToUpdate)) {
1515 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1517 .on(this::throwComponentException);
1521 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1522 for (GroupDefinition group : groupsFromResource) {
1523 Optional<GroupDefinition> op = groupsAsList.stream()
1524 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1525 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1526 groupsToDelete.add(group);
1531 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1532 for (GroupDefinition group : groupsAsList) {
1533 Optional<GroupDefinition> op = groupsFromResource.stream()
1534 .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1535 if (op.isPresent()) {
1536 GroupDefinition groupToUpdate = op.get();
1537 groupToUpdate.setMembers(group.getMembers());
1538 groupToUpdate.setCapabilities(group.getCapabilities());
1539 groupToUpdate.setProperties(group.getProperties());
1540 groupsToUpdate.add(groupToUpdate);
1542 groupsToCreate.add(group);
1547 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1548 List<InputDefinition> resourceProperties = resource.getInputs();
1549 if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1551 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1553 if (createInputs.isRight()) {
1554 throw new ComponentException(createInputs.right().value());
1559 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1560 .getToscaElement(resource.getUniqueId());
1561 if (updatedResource.isRight()) {
1562 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1563 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1565 return updatedResource.left().value();
1568 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1570 List<GroupDefinition> result = new ArrayList<>();
1571 List<ComponentInstance> componentInstances = component.getComponentInstances();
1573 if (groups != null) {
1574 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1575 if (validateCyclicGroupsDependencies.isRight()) {
1576 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1578 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1579 String groupName = entry.getKey();
1580 GroupDefinition groupDefinition = entry.getValue();
1581 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1582 updatedGroupDefinition.setMembers(null);
1583 Map<String, String> members = groupDefinition.getMembers();
1584 if (members != null) {
1585 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1587 result.add(updatedGroupDefinition);
1593 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1594 Set<String> compInstancesNames = members.keySet();
1596 if (CollectionUtils.isEmpty(componentInstances)) {
1597 String membersAstString = compInstancesNames.stream().collect(joining(","));
1598 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1599 membersAstString, groupName, component.getNormalizedName());
1600 throw new ComponentException(componentsUtils.getResponseFormat(
1601 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1602 component.getNormalizedName(), getComponentTypeForResponse(component)));
1604 // Find all component instances with the member names
1605 Map<String, String> memberNames = componentInstances.stream()
1606 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1607 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1608 Map<String, String> relevantInstances = memberNames.entrySet().stream()
1609 .filter(n -> compInstancesNames.contains(n.getKey()))
1610 .collect(toMap(Entry::getKey, Entry::getValue));
1612 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1614 List<String> foundMembers = new ArrayList<>();
1615 if (relevantInstances != null) {
1616 foundMembers = relevantInstances.keySet().stream().collect(toList());
1618 compInstancesNames.removeAll(foundMembers);
1619 String membersAstString = compInstancesNames.stream().collect(joining(","));
1620 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1621 groupName, component.getNormalizedName());
1622 throw new ComponentException(componentsUtils.getResponseFormat(
1623 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1624 component.getNormalizedName(), getComponentTypeForResponse(component)));
1626 updatedGroupDefinition.setMembers(relevantInstances);
1630 * This Method validates that there is no cyclic group dependencies. meaning
1631 * group A as member in group B which is member in group A
1636 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1638 Either<Boolean, ResponseFormat> result = Either.left(true);
1640 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1641 while (allGroupsItr.hasNext() && result.isLeft()) {
1642 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1643 // Fetches a group member A
1644 String groupAName = groupAEntry.getKey();
1645 // Finds all group members in group A
1646 Set<String> allGroupAMembersNames = new HashSet<>();
1647 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1648 // If A is a group member of itself found cyclic dependency
1649 if (allGroupAMembersNames.contains(groupAName)) {
1650 ResponseFormat responseFormat = componentsUtils
1651 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1652 result = Either.right(responseFormat);
1655 } catch (Exception e) {
1656 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1657 result = Either.right(responseFormat);
1658 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1664 * This Method fills recursively the set groupMembers with all the members
1665 * of the given group which are also of type group.
1669 * @param allGroupMembers
1672 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1673 Set<String> allGroupMembers) {
1675 // Found Cyclic dependency
1676 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1679 GroupDefinition groupDefinition = allGroups.get(groupName);
1680 // All Members Of Current Group Resource Instances & Other Groups
1681 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1682 // Filtered Members Of Current Group containing only members which
1684 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1685 // Keep Only Elements of type group and not Resource Instances
1686 filter(allGroups::containsKey).
1687 // Add Filtered Elements to main Set
1688 peek(allGroupMembers::add).
1692 // Recursively call the method for all the filtered group members
1693 for (String innerGroupName : currGroupFilteredMembers) {
1694 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1699 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
1700 Set<String> allGroupMembers) {
1702 boolean stop = false;
1703 // In Case Not Group Stop
1704 if (!allGroups.containsKey(groupName)) {
1707 // In Case Group Has no members stop
1709 GroupDefinition groupDefinition = allGroups.get(groupName);
1710 stop = isEmpty(groupDefinition.getMembers());
1713 // In Case all group members already contained stop
1715 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1716 Set<String> membersOfTypeGroup = allMembers.stream().
1717 // Filter In Only Group members
1718 filter(allGroups::containsKey).
1721 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1726 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1727 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1728 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1729 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1730 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1733 log.debug("************* Going to create all nodes {}", yamlName);
1734 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1735 nodeTypesInfo, csarInfo, nodeName);
1736 log.debug("************* Finished to create all nodes {}", yamlName);
1737 log.debug("************* Going to create all resource instances {}", yamlName);
1738 resource = createResourceInstances(yamlName, resource,
1739 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1740 log.debug("************* Finished to create all resource instances {}", yamlName);
1741 log.debug("************* Going to create all relations {}", yamlName);
1742 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1743 log.debug("************* Finished to create all relations {}", yamlName);
1744 log.debug("************* Going to create positions {}", yamlName);
1745 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1746 log.debug("************* Finished to set positions {}", yamlName);
1750 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
1751 List<ArtifactDefinition> artifactsToAdd) {
1752 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
1754 artifactsToAdd.stream().forEach(a -> {
1755 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1756 vfcArtifacts.add(a);
1758 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1764 @SuppressWarnings("unchecked")
1765 private void handleNodeTypes(String yamlName, Resource resource,
1766 String topologyTemplateYaml, boolean needLock,
1767 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1768 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1769 CsarInfo csarInfo, String nodeName) {
1771 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1772 if (nodeTypeEntry.getValue().isNested()) {
1774 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1775 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1776 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1779 Map<String, Object> mappedToscaTemplate = null;
1780 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
1781 && nodeTypesInfo.containsKey(nodeName)) {
1782 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1784 if (isEmpty(mappedToscaTemplate)) {
1785 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1787 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1788 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1789 } catch(ComponentException e){
1790 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
1791 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1792 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1794 } catch (StorageException e){
1795 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1796 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1799 // add the created node types to the cache although they are not in the
1801 csarInfo.getCreatedNodes().values().stream()
1802 .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1805 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
1806 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1807 boolean inTransaction) {
1809 if (csarInfo.getCsar() != null) {
1810 String vendorLicenseModelId = null;
1811 String vfLicenseModelId = null;
1813 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1814 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1815 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1816 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1817 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1818 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1820 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1821 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1827 // Specific Behavior for license artifacts
1828 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1829 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
1830 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1831 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
1832 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
1834 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1835 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1836 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1837 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
1838 artifactOperation, null, true, shouldLock, inTransaction);
1840 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
1841 createdArtifacts, shouldLock, inTransaction, artifactOperation);
1842 if (eitherCreateResult.isRight()) {
1843 return Either.right(eitherCreateResult.right().value());
1845 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1846 .getToscaElement(resource.getUniqueId());
1847 if (eitherGerResource.isRight()) {
1848 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1849 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1851 return Either.right(responseFormat);
1854 resource = eitherGerResource.left().value();
1856 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1858 if (artifacsMetaCsarStatus.isLeft()) {
1859 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1860 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1861 Either<Resource, ResponseFormat> createArtifactsFromCsar;
1862 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1863 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1865 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1868 if (createArtifactsFromCsar.isRight()) {
1869 log.debug("Couldn't create artifacts from artifacts.meta");
1870 return Either.right(createArtifactsFromCsar.right().value());
1873 return Either.left(createArtifactsFromCsar.left().value());
1876 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
1880 return Either.left(resource);
1884 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
1885 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1886 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1887 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1888 boolean inTransaction) {
1889 byte[] artifactFileBytes = null;
1891 if (csarInfo.getCsar().containsKey(artifactPath)) {
1892 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1894 Either<Boolean, ResponseFormat> result = Either.left(true);
1895 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
1896 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1897 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
1898 shouldLock, inTransaction);
1899 if (handleDelete.isRight()) {
1900 result = Either.right(handleDelete.right().value());
1906 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1907 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1908 ArtifactOperationEnum.CREATE);
1912 if (artifactFileBytes != null) {
1913 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1914 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1915 artifactFileBytes, null, isFromCsar);
1916 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1917 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1918 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1919 if (eitherNonMetaArtifacts.isRight()) {
1920 BeEcompErrorManager.getInstance()
1921 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1922 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1923 ErrorSeverity.WARNING);
1924 return Either.right(eitherNonMetaArtifacts.right().value());
1930 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
1931 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
1935 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
1936 List<ArtifactDefinition> createdArtifacts,
1937 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
1938 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
1939 && eitherNonMetaArtifacts.isLeft()) {
1940 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
1941 if (eitherResult.isLeft()) {
1942 createdArtifacts.add(eitherResult.left().value());
1948 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
1949 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
1950 ArtifactOperationInfo artifactOperation) {
1952 Either<Resource, ResponseFormat> resStatus = null;
1953 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
1956 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
1957 if (artifactPathAndNameList.isRight()) {
1958 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
1959 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
1961 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
1963 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1964 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
1965 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
1967 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
1968 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
1970 if (findVfCsarArtifactsToHandleRes.isRight()) {
1971 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
1973 if (resStatus == null) {
1974 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
1977 if (resStatus == null && vfCsarArtifactsToHandle != null) {
1978 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
1980 if (resStatus == null) {
1981 resStatus = Either.left(resource);
1983 } catch (Exception e) {
1984 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1985 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
1987 CsarUtils.handleWarningMessages(collectedWarningMessages);
1992 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) {
1993 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
1996 Optional<ResponseFormat> optionalCreateInDBError =
1997 // Stream of artifacts to be created
1998 currArtifactOperationPair.getValue().stream()
1999 // create each artifact
2000 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2001 e.getArtifactName(), e.getArtifactType().getType(),
2002 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2003 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2004 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2005 currArtifactOperationPair.getKey()),
2006 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2007 // filter in only error
2008 .filter(Either::isRight).
2009 // Convert the error from either to
2011 map(e -> e.right().value()).
2012 // Check if an error occurred
2014 // Error found on artifact Creation
2015 if (optionalCreateInDBError.isPresent()) {
2016 resStatus = Either.right(optionalCreateInDBError.get());
2023 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
2024 List<NonMetaArtifactInfo> artifactPathAndNameList =
2025 // Stream of file paths contained in csar
2026 csarInfo.getCsar().entrySet().stream()
2027 // Filter in only VF artifact path location
2028 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2030 // Validate and add warnings
2031 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2032 collectedWarningMessages))
2033 // Filter in Non Warnings
2034 .filter(Either::isLeft)
2035 // Convert from Either to NonMetaArtifactInfo
2036 .map(e -> e.left().value())
2039 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2040 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2041 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2042 return Either.right(nonMetaArtifactInfo.getArtifactName());
2045 return Either.left(artifactPathAndNameList);
2048 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2049 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2051 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2052 // collect all Deployment and Informational artifacts of VF
2053 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2054 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2056 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2057 existingArtifacts.addAll(resource.getArtifacts().values());
2059 existingArtifacts = existingArtifacts.stream()
2060 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2061 // was created from HEAT.meta
2062 .filter(this::isNonMetaArtifact).collect(toList());
2064 List<String> artifactsToIgnore = new ArrayList<>();
2065 // collect IDs of Artifacts of VF which belongs to any group
2066 if (resource.getGroups() != null) {
2067 resource.getGroups().stream().forEach(g -> {
2068 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
2069 artifactsToIgnore.addAll(g.getArtifacts());
2073 existingArtifacts = existingArtifacts.stream()
2074 // filter artifacts which belongs to any group
2075 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
2076 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2079 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2080 boolean result = true;
2081 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2087 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2088 boolean result = true;
2089 if (artifact.getArtifactType() == null
2090 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2091 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2097 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
2098 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2099 log.debug("#createResourceInstancesRelations - Going to create relations ");
2100 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2101 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) {
2102 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
2103 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations","No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2104 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
2106 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2107 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2108 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2109 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2110 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2111 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2112 Map<String, Resource> originCompMap = new HashMap<>();
2113 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2114 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2116 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2117 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2118 if (allDataTypes.isRight()) {
2119 TitanOperationStatus status = allDataTypes.right().value();
2120 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2121 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2122 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2123 DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
2126 Resource finalResource = resource;
2127 uploadResInstancesMap
2129 .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2130 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
2131 instArtifacts, instAttributes, originCompMap, instInputs, i));
2133 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2134 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2135 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2136 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2137 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2138 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2140 resource = getResourceAfterCreateRelations(resource);
2142 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2143 associateResourceInstances(yamlName, resource, relations);
2144 handleSubstitutionMappings(resource, uploadResInstancesMap);
2145 log.debug("************* in create relations, getResource start");
2146 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2147 log.debug("************* in create relations, getResource end");
2148 if (eitherGetResource.isRight()) {
2149 throw new ComponentException(componentsUtils.getResponseFormatByResource(
2150 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
2152 return eitherGetResource.left().value();
2155 private Resource getResourceAfterCreateRelations(Resource resource) {
2156 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2157 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2158 .getToscaElement(resource.getUniqueId(), parametersView);
2160 if (eitherGetResource.isRight()) {
2161 throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2163 return eitherGetResource.left().value();
2166 private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2167 StorageOperationStatus addArtToInst;
2168 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2169 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2170 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2172 throw new ComponentException(componentsUtils
2173 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2177 private ComponentParametersView getComponentFilterAfterCreateRelations() {
2178 ComponentParametersView parametersView = new ComponentParametersView();
2179 parametersView.disableAll();
2180 parametersView.setIgnoreComponentInstances(false);
2181 parametersView.setIgnoreComponentInstancesProperties(false);
2182 parametersView.setIgnoreCapabilities(false);
2183 parametersView.setIgnoreRequirements(false);
2184 parametersView.setIgnoreGroups(false);
2185 return parametersView;
2188 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
2189 StorageOperationStatus addArtToInst;
2190 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2191 resource.getUniqueId());
2192 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2193 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2195 throw new ComponentException(componentsUtils
2196 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2200 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2201 StorageOperationStatus addArtToInst;
2202 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2203 resource.getUniqueId());
2204 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2205 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2207 throw new ComponentException(componentsUtils
2208 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2212 private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2213 StorageOperationStatus addArtToInst;
2215 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
2216 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2217 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2218 throw new ComponentException(componentsUtils
2219 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2223 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2224 StorageOperationStatus addArtToInst = toscaOperationFacade
2225 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2226 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2227 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2228 throw new ComponentException(componentsUtils
2229 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2233 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2234 if (MapUtils.isNotEmpty(instInputs)) {
2235 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2236 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2237 if (addInputToInst.isRight()) {
2238 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2239 addInputToInst.right().value());
2240 throw new ComponentException(componentsUtils.getResponseFormat(
2241 componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2246 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2247 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2248 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2249 if (addPropToInst.isRight()) {
2250 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2251 addPropToInst.right().value());
2252 throw new ComponentException(componentsUtils.getResponseFormat(
2253 componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2257 private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2258 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2259 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2260 if (getResourceRes.isRight()) {
2261 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2262 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2263 throw new ComponentException(responseFormat);
2265 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2266 uploadResInstancesMap);
2267 if (getResourceRes.isRight()) {
2268 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2269 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2270 throw new ComponentException(responseFormat);
2275 private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2276 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2277 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2278 ComponentInstance currentCompInstance = null;
2279 for (ComponentInstance compInstance : componentInstancesList) {
2281 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2282 currentCompInstance = compInstance;
2287 if (currentCompInstance == null) {
2288 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2289 resource.getUniqueId());
2290 BeEcompErrorManager.getInstance().logInternalDataError(
2291 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2292 resource.getUniqueId(), ErrorSeverity.ERROR);
2293 ResponseFormat responseFormat = componentsUtils
2294 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2295 throw new ComponentException(responseFormat);
2298 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2299 if (addRelationToRiRes.getStatus() != 200) {
2300 throw new ComponentException(addRelationToRiRes);
2305 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) {
2306 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2307 .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
2309 if (!currentCompInstanceOpt.isPresent()) {
2310 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2311 resource.getUniqueId());
2312 BeEcompErrorManager.getInstance().logInternalDataError(
2313 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2314 resource.getUniqueId(), ErrorSeverity.ERROR);
2315 ResponseFormat responseFormat = componentsUtils
2316 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2317 throw new ComponentException(responseFormat);
2319 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2320 String resourceInstanceId = currentCompInstance.getUniqueId();
2321 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
2322 if (isNotEmpty(originResource.getRequirements())) {
2323 instRequirements.put(currentCompInstance, originResource.getRequirements());
2325 if (isNotEmpty(originResource.getCapabilities())) {
2326 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2327 currentCompInstance, originResource);
2329 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
2330 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2332 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2333 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2335 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2336 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2338 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2339 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2340 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
2341 if (addPropertiesValueToRiRes.getStatus() != 200) {
2342 throw new ComponentException(addPropertiesValueToRiRes);
2345 addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2346 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
2350 private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2351 Resource originResource;
2352 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2353 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2354 .getToscaFullElement(currentCompInstance.getComponentUid());
2355 if (getOriginResourceRes.isRight()) {
2356 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2357 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2358 getOriginResourceRes);
2359 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2360 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2361 throw new ComponentException(responseFormat);
2363 originResource = getOriginResourceRes.left().value();
2364 originCompMap.put(originResource.getUniqueId(), originResource);
2366 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2368 return originResource;
2371 private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2372 Map<String, List<CapabilityDefinition>> originCapabilities;
2373 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2374 originCapabilities = new HashMap<>();
2375 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2376 originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v));
2377 uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
2378 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2380 originCapabilities = originResource.getCapabilities();
2382 instCapabilties.put(currentCompInstance, originCapabilities);
2385 private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2386 originCapabilities.values().stream()
2387 .flatMap(Collection::stream)
2388 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2389 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2392 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2393 for (UploadCapInfo capability : capabilities) {
2394 if (isNotEmpty(capability.getProperties())) {
2395 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2396 .collect(toMap(UploadInfo::getName, p -> p)));
2401 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2402 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2404 originCapabilities.put(type, list);
2407 private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2408 Map<String, DataTypeDefinition> allDataTypes) {
2409 properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2412 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2413 Map<String, DataTypeDefinition> allDataTypes) {
2414 String value = null;
2415 List<GetInputValueDataDefinition> getInputs = null;
2416 boolean isValidate = true;
2417 if (null != propertyInfo && propertyInfo.getValue() != null) {
2418 getInputs = propertyInfo.getGet_input();
2419 isValidate = getInputs == null || getInputs.isEmpty();
2421 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2423 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2424 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2427 property.setValue(value);
2428 return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2431 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2432 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2433 Either<Resource, StorageOperationStatus> updateRes = null;
2434 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2435 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2436 StorageOperationStatus status = toscaOperationFacade
2437 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2438 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2440 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2441 resource.getUniqueId(), status);
2442 updateRes = Either.right(status);
2444 if (updateRes == null) {
2445 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2446 updatedInstCapabilities, updatedInstRequirements);
2447 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2448 resource.getUniqueId());
2449 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2451 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2452 resource.getUniqueId(), status);
2453 updateRes = Either.right(status);
2456 if (updateRes == null) {
2457 updateRes = Either.left(resource);
2462 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2463 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2464 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2465 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2467 componentInstances.stream().forEach(i -> {
2468 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2469 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2470 fillUpdatedInstRequirements(updatedInstRequirements, i,
2471 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2475 private void fillUpdatedInstRequirements(
2476 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2477 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2478 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2479 Set<String> updatedReqNames = new HashSet<>();
2480 if (isNotEmpty(requirementsNamesToUpdate)) {
2481 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2482 updatedRequirements.put(requirements.getKey(),
2483 requirements.getValue().stream()
2484 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2485 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2487 r.setParentName(r.getName());
2488 r.setName(requirementsNamesToUpdate.get(r.getName()));
2489 updatedReqNames.add(r.getName());
2491 }).collect(toList()));
2494 if (isNotEmpty(updatedRequirements)) {
2495 updatedInstRequirements.put(instance, updatedRequirements);
2499 private void fillUpdatedInstCapabilities(
2500 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2501 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2502 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2503 Set<String> updatedCapNames = new HashSet<>();
2504 if (isNotEmpty(capabilitiesNamesToUpdate)) {
2505 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2506 updatedCapabilities.put(requirements.getKey(),
2507 requirements.getValue().stream()
2508 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2509 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2511 c.setParentName(c.getName());
2512 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2513 updatedCapNames.add(c.getName());
2515 }).collect(toList()));
2518 if (isNotEmpty(updatedCapabilities)) {
2519 updatedInstCapabilties.put(instance, updatedCapabilities);
2523 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2524 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2525 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2527 ComponentInstance currentCompInstance = null;
2529 for (ComponentInstance compInstance : componentInstancesList) {
2531 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2532 currentCompInstance = compInstance;
2538 if (currentCompInstance == null) {
2539 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2540 resource.getUniqueId());
2541 BeEcompErrorManager.getInstance().logInternalDataError(
2542 COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2543 resource.getUniqueId(), ErrorSeverity.ERROR);
2544 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2547 String resourceInstanceId = currentCompInstance.getUniqueId();
2549 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2551 if (regMap != null) {
2552 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2554 while (nodesRegValue.hasNext()) {
2555 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2557 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2558 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2559 log.debug("Going to create relation {}", uploadRegInfo.getName());
2560 String regName = uploadRegInfo.getName();
2561 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2562 regCapRelDef.setFromNode(resourceInstanceId);
2563 log.debug("try to find available requirement {} ", regName);
2564 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2565 yamlName, nodesInfoValue, currentCompInstance,
2566 uploadRegInfo.getCapabilityName());
2567 if (eitherReqStatus.isRight()) {
2568 log.debug("failed to find available requirement {} status is {}", regName,
2569 eitherReqStatus.right().value());
2570 return eitherReqStatus.right().value();
2573 RequirementDefinition validReq = eitherReqStatus.left().value();
2574 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2575 .getRelationships();
2576 if (reqAndRelationshipPairList == null) {
2577 reqAndRelationshipPairList = new ArrayList<>();
2579 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2580 reqAndRelationshipPair.setRequirement(regName);
2581 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2582 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2583 RelationshipImpl relationship = new RelationshipImpl();
2584 relationship.setType(validReq.getCapability());
2585 reqAndRelationshipPair.setRelationships(relationship);
2587 ComponentInstance currentCapCompInstance = null;
2588 for (ComponentInstance compInstance : componentInstancesList) {
2589 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2590 currentCapCompInstance = compInstance;
2595 if (currentCapCompInstance == null) {
2596 log.debug("The component instance with name {} not found on resource {} ",
2597 uploadRegInfo.getNode(), resource.getUniqueId());
2598 BeEcompErrorManager.getInstance().logInternalDataError(
2599 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2600 resource.getUniqueId(), ErrorSeverity.ERROR);
2601 return componentsUtils
2602 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2604 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2605 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2606 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2607 currentCapCompInstance, uploadRegInfo);
2608 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2609 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2610 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2611 if (aviableCapForRel == null) {
2612 log.debug("aviable capability was not found. req name is {} component instance is {}",
2613 validReq.getName(), currentCapCompInstance.getUniqueId());
2614 BeEcompErrorManager.getInstance().logInternalDataError(
2615 "aviable capability was not found. req name is " + validReq.getName()
2616 + " component instance is " + currentCapCompInstance.getUniqueId(),
2617 resource.getUniqueId(), ErrorSeverity.ERROR);
2618 return componentsUtils
2619 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2621 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2622 capReqRel.setRelation(reqAndRelationshipPair);
2623 reqAndRelationshipPairList.add(capReqRel);
2624 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2625 relations.add(regCapRelDef);
2628 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
2629 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2631 return componentsUtils.getResponseFormat(ActionStatus.OK);
2634 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2635 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2636 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
2637 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2638 if (MapUtils.isNotEmpty(propMap)) {
2639 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2640 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2642 if (CollectionUtils.isEmpty( originResource.getInputs())) {
2643 log.debug("failed to find properties ");
2644 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2646 originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
2647 for (List<UploadPropInfo> propertyList : propMap.values()) {
2648 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
2650 currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
2651 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2655 private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
2656 UploadPropInfo propertyInfo = propertyList.get(0);
2657 String propName = propertyInfo.getName();
2658 if (!currPropertiesMap.containsKey(propName)) {
2659 log.debug("failed to find property {} ", propName);
2660 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2663 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
2664 ComponentInstanceInput property = null;
2666 String value = null;
2667 List<GetInputValueDataDefinition> getInputs = null;
2668 boolean isValidate = true;
2669 if (propertyInfo.getValue() != null) {
2670 getInputs = propertyInfo.getGet_input();
2671 isValidate = getInputs == null || getInputs.isEmpty();
2673 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2674 curPropertyDef.getType());
2676 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2677 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2680 String innerType = null;
2681 property = new ComponentInstanceInput(curPropertyDef, value, null);
2683 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2685 property.setValue(validPropertyVAlue);
2687 if (isNotEmpty(getInputs)) {
2688 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2689 for (GetInputValueDataDefinition getInput : getInputs) {
2690 List<InputDefinition> inputs = resource.getInputs();
2691 if (CollectionUtils.isEmpty(inputs)) {
2692 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
2693 property, currentCompInstance.getUniqueId());
2694 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2697 Optional<InputDefinition> optional = inputs.stream()
2698 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
2699 if (!optional.isPresent()) {
2700 log.debug("Failed to find input {} ", getInput.getInputName());
2701 // @@TODO error message
2702 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2704 InputDefinition input = optional.get();
2705 getInput.setInputId(input.getUniqueId());
2706 getInputValues.add(getInput);
2708 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2709 processGetInput(getInputValues, inputs, getInputIndex);
2711 property.setGetInputValues(getInputValues);
2713 instPropList.add(property);
2714 // delete overriden property
2715 currPropertiesMap.remove(property.getName());
2718 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
2719 Optional<InputDefinition> optional;
2720 if (getInputIndex != null) {
2721 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
2723 if (!optional.isPresent()) {
2724 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2725 // @@TODO error message
2726 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2728 InputDefinition inputIndex = optional.get();
2729 getInputIndex.setInputId(inputIndex.getUniqueId());
2730 getInputValues.add(getInputIndex);
2734 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
2735 String propName = prop.getName();
2736 if (!currPropertiesMap.containsKey(propName)) {
2737 currPropertiesMap.put(propName, prop);
2741 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2742 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2743 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
2745 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2746 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2748 List<PropertyDefinition> listFromMap = originResource.getProperties();
2749 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
2750 log.debug("failed to find properties ");
2751 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2753 if (listFromMap == null || listFromMap.isEmpty()) {
2754 return componentsUtils.getResponseFormat(ActionStatus.OK);
2756 for (PropertyDefinition prop : listFromMap) {
2757 String propName = prop.getName();
2758 if (!currPropertiesMap.containsKey(propName)) {
2759 currPropertiesMap.put(propName, prop);
2762 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2763 if (propMap != null && propMap.size() > 0) {
2764 for (List<UploadPropInfo> propertyList : propMap.values()) {
2766 UploadPropInfo propertyInfo = propertyList.get(0);
2767 String propName = propertyInfo.getName();
2768 if (!currPropertiesMap.containsKey(propName)) {
2769 log.debug("failed to find property {} ", propName);
2770 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2773 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2774 ComponentInstanceProperty property = null;
2776 String value = null;
2777 List<GetInputValueDataDefinition> getInputs = null;
2778 boolean isValidate = true;
2779 if (propertyInfo.getValue() != null) {
2780 getInputs = propertyInfo.getGet_input();
2781 isValidate = getInputs == null || getInputs.isEmpty();
2783 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2784 curPropertyDef.getType());
2786 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2787 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2790 String innerType = null;
2791 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2793 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2794 property.setValue(validatePropValue);
2796 if (getInputs != null && !getInputs.isEmpty()) {
2797 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2798 for (GetInputValueDataDefinition getInput : getInputs) {
2799 List<InputDefinition> inputs = resource.getInputs();
2800 if (inputs == null || inputs.isEmpty()) {
2801 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2802 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2804 .map(GetInputValueDataDefinition::getInputName)
2805 .collect(toList()).toString());
2807 InputDefinition input = findInputByName(inputs, getInput);
2808 getInput.setInputId(input.getUniqueId());
2809 getInputValues.add(getInput);
2811 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2812 if (getInputIndex != null) {
2813 input = findInputByName(inputs, getInputIndex);
2814 getInputIndex.setInputId(input.getUniqueId());
2815 getInputValues.add(getInputIndex);
2820 property.setGetInputValues(getInputValues);
2822 instPropList.add(property);
2823 // delete overriden property
2824 currPropertiesMap.remove(property.getName());
2827 // add rest of properties
2828 if (!currPropertiesMap.isEmpty()) {
2829 for (PropertyDefinition value : currPropertiesMap.values()) {
2830 instPropList.add(new ComponentInstanceProperty(value));
2833 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2834 return componentsUtils.getResponseFormat(ActionStatus.OK);
2837 // US740820 Relate RIs according to capability name
2838 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
2839 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2840 if (null == uploadReqInfo.getCapabilityName()
2841 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
2845 return findAvailableCapability(validReq, currentCapCompInstance);
2847 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
2850 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
2851 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2852 CapabilityDefinition cap = null;
2853 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
2854 if (!capMap.containsKey(validReq.getCapability())) {
2857 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
2858 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
2859 if (!capByName.isPresent()) {
2862 cap = capByName.get();
2864 if (isBoundedByOccurrences(cap)) {
2865 String leftOccurrences = cap.getLeftOccurrences();
2866 int left = Integer.parseInt(leftOccurrences);
2869 cap.setLeftOccurrences(String.valueOf(left));
2877 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
2878 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
2879 if (capMap.containsKey(validReq.getCapability())) {
2880 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
2882 for (CapabilityDefinition cap : capList) {
2883 if (isBoundedByOccurrences(cap)) {
2884 String leftOccurrences = cap.getLeftOccurrences() != null ?
2885 cap.getLeftOccurrences() : cap.getMaxOccurrences();
2886 int left = Integer.parseInt(leftOccurrences);
2889 cap.setLeftOccurrences(String.valueOf(left));
2900 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
2901 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
2904 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
2905 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2907 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
2908 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
2909 RequirementDefinition validRegDef = null;
2911 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
2912 for (RequirementDefinition reqDef : entry.getValue()) {
2913 if (reqDef.getName().equals(regName)) {
2914 if (reqDef.getMaxOccurrences() != null
2915 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2916 String leftOccurrences = reqDef.getLeftOccurrences();
2917 if (leftOccurrences == null) {
2918 leftOccurrences = reqDef.getMaxOccurrences();
2920 int left = Integer.parseInt(leftOccurrences);
2923 reqDef.setLeftOccurrences(String.valueOf(left));
2924 validRegDef = reqDef;
2930 validRegDef = reqDef;
2936 if (validRegDef != null) {
2941 for (RequirementDefinition reqDef : list) {
2942 if (reqDef.getName().equals(regName)) {
2943 if (reqDef.getMaxOccurrences() != null
2944 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2945 String leftOccurrences = reqDef.getLeftOccurrences();
2946 if (leftOccurrences == null) {
2947 leftOccurrences = reqDef.getMaxOccurrences();
2949 int left = Integer.parseInt(leftOccurrences);
2952 reqDef.setLeftOccurrences(String.valueOf(left));
2953 validRegDef = reqDef;
2959 validRegDef = reqDef;
2965 if (validRegDef == null) {
2966 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2967 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2968 return Either.right(responseFormat);
2970 return Either.left(validRegDef);
2973 private Resource createResourceInstances(String yamlName, Resource resource,
2974 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2975 Map<String, Resource> nodeNamespaceMap) {
2977 Either<Resource, ResponseFormat> eitherResource = null;
2978 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2979 if (isEmpty(uploadResInstancesMap)) {
2980 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2981 throw new ComponentException(responseFormat);
2983 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2984 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2985 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2987 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2988 uploadResInstancesMap
2990 .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2992 if (isNotEmpty(resourcesInstancesMap)) {
2993 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
2994 resourcesInstancesMap, false);
2995 if (status != null && status != StorageOperationStatus.OK) {
2996 log.debug("Failed to add component instances to container component {}", resource.getName());
2997 ResponseFormat responseFormat = componentsUtils
2998 .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
2999 eitherResource = Either.right(responseFormat);
3000 throw new ComponentException(eitherResource.right().value());
3003 log.debug("*************Going to get resource {}", resource.getUniqueId());
3004 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
3005 .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
3006 log.debug("*************finished to get resource {}", resource.getUniqueId());
3007 if (eitherGetResource.isRight()) {
3008 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3009 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3010 throw new ComponentException(responseFormat);
3012 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) {
3013 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3014 BeEcompErrorManager.getInstance().logBeDaoSystemError(
3015 "Error when create resource instance from csar. ComponentInstances list empty");
3016 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3018 return eitherGetResource.left().value();
3021 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3022 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
3023 Either<Resource, ResponseFormat> eitherResource;
3024 log.debug("*************Going to create resource instances {}", yamlName);
3025 // updating type if the type is node type name - we need to take the
3027 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3028 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3029 uploadComponentInstanceInfo
3030 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3032 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3033 existingnodeTypeMap);
3035 ComponentInstance componentInstance = new ComponentInstance();
3036 componentInstance.setComponentUid(refResource.getUniqueId());
3037 ComponentTypeEnum containerComponentType = resource.getComponentType();
3038 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3039 if (containerNodeType.equals(NodeTypeEnum.Resource)
3040 && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3041 && isNotEmpty(refResource.getCapabilities())) {
3042 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3043 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3044 refResource.getUniqueId(), refResource.getCapabilities(),
3045 uploadComponentInstanceInfo.getCapabilities());
3046 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3048 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3050 "createResourceInstances - not found lates version for resource instance with name {} and type ",
3051 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3052 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3053 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3054 throw new ComponentException(responseFormat);
3056 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3057 componentInstance.setName(uploadComponentInstanceInfo.getName());
3058 componentInstance.setIcon(origResource.getIcon());
3059 resourcesInstancesMap.put(componentInstance, origResource);
3062 private ComponentParametersView getComponentWithInstancesFilter() {
3063 ComponentParametersView parametersView = new ComponentParametersView();
3064 parametersView.disableAll();
3065 parametersView.setIgnoreComponentInstances(false);
3066 parametersView.setIgnoreInputs(false);
3067 // inputs are read when creating
3068 // property values on instances
3069 parametersView.setIgnoreUsers(false);
3070 return parametersView;
3073 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3074 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3075 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3076 if (originCapabilities.containsKey(currEntry.getKey())) {
3077 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3080 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3081 capabilities.getValue().stream().forEach(cap -> {
3082 if (uploadedCapabilities.containsKey(cap.getName())) {
3083 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3084 c.setName(cap.getName());
3085 c.setType(cap.getType());
3093 private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
3094 Map<String, Resource> nodeNamespaceMap) {
3096 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3097 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3098 Resource refResource;
3099 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3100 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3102 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3103 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3104 if (findResourceEither.isRight()) {
3106 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3107 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3108 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3109 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3110 throw new ComponentException(responseFormat);
3112 refResource = findResourceEither.left().value();
3113 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3115 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3116 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3118 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3119 refResource.getName(), componentState);
3120 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3121 refResource.getComponentType().getValue(), refResource.getName(), componentState);
3122 throw new ComponentException(responseFormat);
3125 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3126 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3127 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3128 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3129 throw new ComponentException(responseFormat);
3135 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
3136 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3137 boolean forceCertificationAllowed) {
3139 Either<Resource, ResponseFormat> result = null;
3141 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3142 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3143 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3144 if (result.isRight()) {
3147 resource = result.left().value();
3149 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3150 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
3151 resource, user, false, inTransaction, needLock);
3152 result = eitherPopulated.isLeft() ? Either.left(resource)
3153 : Either.right(eitherPopulated.right().value());
3156 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3157 } catch (Exception e) {
3158 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3159 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3161 if (result == null || result.isRight()) {
3162 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3163 if (!inTransaction) {
3164 titanDao.rollback();
3166 } else if (!inTransaction) {
3172 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
3173 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3174 return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
3175 lifecycleChangeInfo, inTransaction, needLock);
3178 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
3179 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3180 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3184 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
3185 Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
3186 CsarInfo csarInfo, String nodeName, boolean isNested) {
3188 ImmutablePair<Resource, ActionStatus> result = null;
3189 // check if resource already exists (search by tosca name = type)
3190 boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3191 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3192 .getLatestByToscaResourceName(resource.getToscaResourceName());
3194 if (latestByToscaName.isLeft()) {
3195 Resource foundResource = latestByToscaName.left().value();
3196 // we don't allow updating names of top level types
3197 if (!isNestedResource &&
3198 !StringUtils.equals(resource.getName(), foundResource.getName())) {
3199 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3200 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3201 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3202 foundResource.getName(), resource.getToscaResourceName());
3203 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3204 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3205 throwComponentException(responseFormat);
3207 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3208 } else if (isNotFound(latestByToscaName)) {
3209 if (isNestedResource) {
3210 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
3212 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3215 StorageOperationStatus status = latestByToscaName.right().value();
3216 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3217 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3218 componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
3219 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3220 throwComponentException(responseFormat);
3225 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3226 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3229 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
3230 Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
3231 resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
3232 if (latestByToscaName.isLeft()) {
3233 Resource nestedResource = (Resource) latestByToscaName.left().value();
3234 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3235 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
3236 ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3237 if (eitherValidation.isRight()) {
3238 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3240 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3242 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3246 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3247 return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
3250 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
3251 User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3252 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3253 validateResourceBeforeCreate(resource, user,
3254 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3255 Resource createdResource = createResourceByDao(resource, user,
3256 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
3257 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
3258 ActionStatus.CREATED);
3259 ASDCKpiApi.countImportResourcesKPI();
3260 return resourcePair;
3263 public boolean isResourceExist(String resourceName) {
3264 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3265 return latestByName.isLeft();
3268 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3269 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3271 String lockedResourceId = oldResource.getUniqueId();
3272 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3273 oldResource.getVersion(), oldResource.getLifecycleState());
3274 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3276 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3277 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3278 mergeOldResourceMetadataWithNew(oldResource, newResource);
3280 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3281 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3282 // contact info normalization
3283 newResource.setContactId(newResource.getContactId().toLowerCase());
3284 // non-updatable fields
3285 newResource.setCreatorUserId(user.getUserId());
3286 newResource.setCreatorFullName(user.getFullName());
3287 newResource.setLastUpdaterUserId(user.getUserId());
3288 newResource.setLastUpdaterFullName(user.getFullName());
3289 newResource.setUniqueId(oldResource.getUniqueId());
3290 newResource.setVersion(oldResource.getVersion());
3291 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3292 newResource.setLifecycleState(oldResource.getLifecycleState());
3293 newResource.setUUID(oldResource.getUUID());
3294 newResource.setNormalizedName(oldResource.getNormalizedName());
3295 newResource.setSystemName(oldResource.getSystemName());
3296 if (oldResource.getCsarUUID() != null) {
3297 newResource.setCsarUUID(oldResource.getCsarUUID());
3299 if (oldResource.getImportedToscaChecksum() != null) {
3300 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3302 newResource.setAbstract(oldResource.isAbstract());
3304 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
3305 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3307 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3308 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3310 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3311 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3314 // created without tosca artifacts - add the placeholders
3315 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3316 setToscaArtifactsPlaceHolders(newResource, user);
3318 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3319 .overrideComponent(newResource, oldResource);
3321 if (overrideResource.isRight()) {
3322 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3323 componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3324 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3326 throwComponentException(responseFormat);
3329 log.debug("Resource updated successfully!!!");
3330 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3331 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3332 ResourceVersionInfo.newBuilder()
3333 .state(oldResource.getLifecycleState()
3335 .version(oldResource.getVersion())
3338 resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3340 return resourcePair;
3342 if (resourcePair == null) {
3343 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3344 titanDao.rollback();
3345 } else if (!inTransaction) {
3349 log.debug("unlock resource {}", lockedResourceId);
3350 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3357 * Merge old resource with new. Keep old category and vendor name without
3360 * @param oldResource
3361 * @param newResource
3363 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3365 // keep old category and vendor name without change
3366 // merge the rest of the resource metadata
3367 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3368 newResource.setTags(oldResource.getTags());
3371 if (newResource.getDescription() == null) {
3372 newResource.setDescription(oldResource.getDescription());
3375 if (newResource.getVendorRelease() == null) {
3376 newResource.setVendorRelease(oldResource.getVendorRelease());
3379 if (newResource.getResourceVendorModelNumber() == null) {
3380 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3383 if (newResource.getContactId() == null) {
3384 newResource.setContactId(oldResource.getContactId());
3387 newResource.setCategories(oldResource.getCategories());
3388 if (newResource.getVendorName() == null) {
3389 newResource.setVendorName(oldResource.getVendorName());
3393 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3394 boolean inTransaction, boolean needLock) {
3396 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3398 return lifecycleBusinessLogic.changeState(
3399 oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3400 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3402 .on(response -> failOnChangeState(response, user, oldResource, newResource));
3407 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3408 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3409 response.getFormattedMessage());
3410 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3411 ResourceVersionInfo.newBuilder()
3412 .state(oldResource.getLifecycleState().name())
3413 .version(oldResource.getVersion())
3415 throw new ComponentException(response);
3418 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3420 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3421 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3422 validateLifecycleTypesCreate(user, resource, actionEnum);
3423 validateResourceType(user, resource, actionEnum);
3424 resource.setCreatorUserId(user.getUserId());
3425 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3426 resource.setContactId(resource.getContactId().toLowerCase());
3427 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3428 String resourceSystemName;
3429 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3430 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3432 resourceSystemName = resource.getSystemName();
3434 resource.setToscaResourceName(CommonBeUtils
3435 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3438 // Generate invariant UUID - must be here and not in operation since it
3439 // should stay constant during clone
3441 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3442 resource.setInvariantUUID(invariantUUID);
3447 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3448 AuditingActionEnum actionEnum) {
3449 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3450 if (resource.getResourceType() == null) {
3451 log.debug("Invalid resource type for resource");
3452 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3453 eitherResult = Either.right(errorResponse);
3454 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3456 return eitherResult;
3459 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3460 AuditingActionEnum actionEnum) {
3461 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3462 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3463 log.debug("validate interface lifecycle Types Exist");
3464 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3465 while (intItr.hasNext() && eitherResult.isLeft()) {
3466 InterfaceDefinition interfaceDefinition = intItr.next();
3467 String intType = interfaceDefinition.getUniqueId();
3468 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3469 .getInterface(intType);
3470 if (eitherCapTypeFound.isRight()) {
3471 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3472 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3473 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3474 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3475 intType, resource.getName());
3476 BeEcompErrorManager.getInstance()
3477 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3478 log.debug("request to data model failed with error: {}",
3479 eitherCapTypeFound.right().value().name());
3482 ResponseFormat errorResponse = componentsUtils
3483 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3484 eitherResult = Either.right(errorResponse);
3485 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3490 return eitherResult;
3493 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3494 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3495 boolean inTransaction) {
3497 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3498 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3499 log.debug("validate capability Types Exist - capabilities section");
3501 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3503 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3504 eitherResult, typeEntry, inTransaction);
3505 if (eitherResult.isRight()) {
3506 return Either.right(eitherResult.right().value());
3511 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3512 log.debug("validate capability Types Exist - requirements section");
3513 for (String type : resource.getRequirements().keySet()) {
3514 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3515 resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3516 if (eitherResult.isRight()) {
3517 return Either.right(eitherResult.right().value());
3522 return eitherResult;
3525 // @param typeObject- the object to which the validation is done
3526 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3527 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3528 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3529 boolean inTransaction) {
3530 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3531 .getCapabilityType(type, inTransaction);
3532 if (eitherCapTypeFound.isRight()) {
3533 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3534 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3535 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3536 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3537 resource.getName());
3538 BeEcompErrorManager.getInstance()
3539 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3541 log.debug("Trying to get capability type {} failed with error: {}", type,
3542 eitherCapTypeFound.right().value().name());
3543 ResponseFormat errorResponse = null;
3545 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3547 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3550 eitherResult = Either.right(errorResponse);
3551 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3553 return eitherResult;
3556 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3557 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3558 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3559 boolean inTransaction) {
3560 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3561 .getCapabilityType(typeEntry.getKey(), inTransaction);
3562 if (eitherCapTypeFound.isRight()) {
3563 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3564 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3565 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3566 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3567 typeEntry.getKey(), resource.getName());
3568 BeEcompErrorManager.getInstance()
3569 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3571 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3572 eitherCapTypeFound.right().value().name());
3573 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3574 typeEntry.getKey());
3575 eitherResult = Either.right(errorResponse);
3576 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3578 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3579 if (capabilityTypeDefinition.getProperties() != null) {
3580 for (CapabilityDefinition capDef : typeEntry.getValue()) {
3581 List<ComponentInstanceProperty> properties = capDef.getProperties();
3582 if (properties == null || properties.isEmpty()) {
3583 properties = new ArrayList<>();
3584 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3585 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3586 properties.add(newProp);
3589 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3590 PropertyDefinition porpFromDef = prop.getValue();
3591 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3592 for (ComponentInstanceProperty cip : properties) {
3593 if (!cip.getName().equals(porpFromDef.getName())) {
3594 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3595 propsToAdd.add(newProp);
3598 if (!propsToAdd.isEmpty()) {
3599 properties.addAll(propsToAdd);
3603 capDef.setProperties(properties);
3606 return eitherResult;
3609 public Resource createResourceByDao(Resource resource, User user,
3610 AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3613 // lock new resource name in order to avoid creation resource with same
3615 Resource createdResource = null;
3616 if (!inTransaction) {
3617 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3619 if (lockResult.isRight()) {
3620 ResponseFormat responseFormat = lockResult.right().value();
3621 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3622 throw new ComponentException(responseFormat);
3625 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3628 if (resource.deriveFromGeneric()) {
3629 handleResourceGenericType(resource);
3631 createdResource = createResourceTransaction(resource, user, isNormative
3633 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3634 createdResource, actionEnum);
3635 ASDCKpiApi.countCreatedResourcesKPI();
3636 } catch(ComponentException e) {
3637 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
3638 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3640 } catch (StorageException e){
3641 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3642 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3646 if (!inTransaction) {
3647 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3648 NodeTypeEnum.Resource);
3651 return createdResource;
3654 private Resource createResourceTransaction(Resource resource, User user,
3655 boolean isNormative) {
3656 // validate resource name uniqueness
3657 log.debug("validate resource name");
3658 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3659 resource.getName(), resource.getResourceType(), resource.getComponentType());
3660 if (eitherValidation.isRight()) {
3661 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3662 eitherValidation.right().value());
3663 ResponseFormat errorResponse = componentsUtils
3664 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3665 throw new ComponentException(errorResponse);
3667 if (eitherValidation.left().value()) {
3668 log.debug("resource with name: {}, already exists", resource.getName());
3669 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3670 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3671 throw new ComponentException(errorResponse);
3674 log.debug("send resource {} to dao for create", resource.getName());
3676 createArtifactsPlaceHolderData(resource, user);
3679 log.debug("enrich resource with creator, version and state");
3680 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3681 resource.setVersion(INITIAL_VERSION);
3682 resource.setHighestVersion(true);
3683 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3684 resource.setAbstract(false);
3687 return toscaOperationFacade.createToscaComponent(resource)
3689 .on(r->throwComponentExceptionByResource(r, resource));
3692 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3693 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3694 componentsUtils.convertFromStorageResponse(status), resource);
3695 throw new ComponentException(responseFormat);
3698 private void createArtifactsPlaceHolderData(Resource resource, User user) {
3699 // create mandatory artifacts
3701 // TODO it must be removed after that artifact uniqueId creation will be
3702 // moved to ArtifactOperation
3704 setInformationalArtifactsPlaceHolder(resource, user);
3705 setDeploymentArtifactsPlaceHolder(resource, user);
3706 setToscaArtifactsPlaceHolders(resource, user);
3709 @SuppressWarnings("unchecked")
3711 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3712 Resource resource = (Resource) component;
3713 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3714 if (artifactMap == null) {
3715 artifactMap = new HashMap<>();
3717 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3718 .getConfiguration().getDeploymentResourceArtifacts();
3719 if (deploymentResourceArtifacts != null) {
3720 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3721 deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3723 resource.setDeploymentArtifacts(artifactMap);
3726 private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3727 boolean shouldCreateArtifact = true;
3728 Map<String, Object> artifactDetails = (Map<String, Object>) v;
3729 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3730 if (object != null) {
3731 List<String> artifactTypes = (List<String>) object;
3732 if (!artifactTypes.contains(resource.getResourceType().name())) {
3733 shouldCreateArtifact = false;
3737 log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3740 if (shouldCreateArtifact) {
3741 if (artifactsBusinessLogic != null) {
3742 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3743 resource.getUniqueId(), k, (Map<String, Object>) v,
3744 user, ArtifactGroupTypeEnum.DEPLOYMENT);
3745 if (artifactDefinition != null
3746 && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3747 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3753 @SuppressWarnings("unchecked")
3754 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3755 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3756 if (artifactMap == null) {
3757 artifactMap = new HashMap<>();
3759 String resourceUniqueId = resource.getUniqueId();
3760 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3761 .getExcludeResourceCategory();
3762 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3763 .getExcludeResourceType();
3764 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3765 .getConfiguration().getInformationalResourceArtifacts();
3766 List<CategoryDefinition> categories = resource.getCategories();
3767 boolean isCreateArtifact = true;
3768 if (exludeResourceCategory != null) {
3769 String category = categories.get(0).getName();
3770 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3772 if (isCreateArtifact && exludeResourceType != null) {
3773 String resourceType = resource.getResourceType().name();
3774 isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3776 if (informationalResourceArtifacts != null && isCreateArtifact) {
3777 Set<String> keys = informationalResourceArtifacts.keySet();
3778 for (String informationalResourceArtifactName : keys) {
3779 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3780 .get(informationalResourceArtifactName);
3781 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3782 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3783 ArtifactGroupTypeEnum.INFORMATIONAL);
3784 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3788 resource.setArtifacts(artifactMap);
3798 public ResponseFormat deleteResource(String resourceId, User user) {
3799 ResponseFormat responseFormat;
3800 validateUserExists(user, DELETE_RESOURCE, false);
3802 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3803 if (resourceStatus.isRight()) {
3804 log.debug("failed to get resource {}", resourceId);
3805 return componentsUtils
3806 .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3809 Resource resource = resourceStatus.left().value();
3811 StorageOperationStatus result = StorageOperationStatus.OK;
3812 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3813 if (lockResult.isRight()) {
3814 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3819 result = markComponentToDelete(resource);
3820 if (result.equals(StorageOperationStatus.OK)) {
3821 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3823 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3824 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3826 return responseFormat;
3829 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3830 titanDao.rollback();
3834 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3839 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3840 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3841 validateUserExists(user, DELETE_RESOURCE, false);
3842 Resource resource = null;
3843 StorageOperationStatus result = StorageOperationStatus.OK;
3846 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3847 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3848 if (resourceStatus.isRight()) {
3849 log.debug("failed to get resource {} version {}", resourceName, version);
3850 return componentsUtils.getResponseFormatByResource(
3851 componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3854 resource = resourceStatus.left().value();
3857 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3858 titanDao.rollback();
3859 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3860 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3865 if (resource != null) {
3866 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3868 if (lockResult.isRight()) {
3869 result = StorageOperationStatus.GENERAL_ERROR;
3870 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3873 result = markComponentToDelete(resource);
3874 if (!result.equals(StorageOperationStatus.OK)) {
3875 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3876 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3877 return responseFormat;
3881 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3882 titanDao.rollback();
3886 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3889 return responseFormat;
3892 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3895 validateUserExists(user, CREATE_RESOURCE, false);
3898 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3899 if (storageStatus.isRight()) {
3900 log.debug("failed to get resource by id {}", resourceId);
3901 return Either.right(componentsUtils.getResponseFormatByResource(
3902 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3904 if (!(storageStatus.left().value() instanceof Resource)) {
3905 return Either.right(componentsUtils.getResponseFormatByResource(
3906 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
3908 return Either.left(storageStatus.left().value());
3912 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
3915 validateUserExists(userId, "get Resource By Name And Version", false);
3917 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
3918 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
3919 if (getResource.isRight()) {
3920 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
3921 return Either.right(componentsUtils.getResponseFormatByResource(
3922 componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
3924 return Either.left(getResource.left().value());
3928 * updateResourceMetadata
3930 * @param user - modifier data (userId)
3931 * @param inTransaction TODO
3932 * @param resourceIdToUpdate - the resource identifier
3933 * @param newResource
3934 * @return Either<Resource , responseFormat>
3936 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
3937 Resource currentResource, User user, boolean inTransaction) {
3939 validateUserExists(user.getUserId(), "update Resource Metadata", false);
3941 log.debug("Get resource with id {}", resourceIdToUpdate);
3942 boolean needToUnlock = false;
3943 boolean rollbackNeeded = true;
3946 if (currentResource == null) {
3947 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
3948 .getToscaElement(resourceIdToUpdate);
3949 if (storageStatus.isRight()) {
3950 throw new ComponentException(componentsUtils.getResponseFormatByResource(
3951 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
3954 currentResource = storageStatus.left().value();
3956 // verify that resource is checked-out and the user is the last
3958 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
3959 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3963 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
3964 NodeTypeEnum.Resource);
3965 if (!lockResult.equals(StorageOperationStatus.OK)) {
3966 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
3967 NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
3968 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
3969 ResponseFormat responseFormat = componentsUtils
3970 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
3971 throw new ComponentException(responseFormat);
3974 needToUnlock = true;
3976 // critical section starts here
3977 // convert json to object
3979 // Update and updated resource must have a non-empty "derivedFrom"
3981 // This code is not called from import resources, because of root
3982 // VF "derivedFrom" should be null (or ignored)
3983 if (ModelConverter.isAtomicComponent(currentResource)) {
3984 validateDerivedFromNotEmpty(null, newResource, null);
3985 validateDerivedFromNotEmpty(null, currentResource, null);
3987 newResource.setDerivedFrom(null);
3990 Either<Boolean, ResponseFormat> validateAndUpdateInterfacesEither = validateAndUpdateInterfaces(resourceIdToUpdate, newResource);
3991 if (validateAndUpdateInterfacesEither.isRight()) {
3992 log.error("failed to validate and update Interfaces");
3993 rollbackNeeded = true;
3994 throw new ComponentException(validateAndUpdateInterfacesEither.right().value());
3997 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
3998 user, currentResource, false, true);
3999 if (dataModelResponse.isRight()) {
4000 log.debug("failed to update resource metadata!!!");
4001 rollbackNeeded = true;
4002 throw new ComponentException(dataModelResponse.right().value());
4005 log.debug("Resource metadata updated successfully!!!");
4006 rollbackNeeded = false;
4007 return dataModelResponse.left().value();
4009 } catch (ComponentException|StorageException e){
4010 rollback(inTransaction, newResource, null, null);
4014 if (!inTransaction) {
4018 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4023 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4024 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4025 updateVfModuleGroupsNames(currentResource, newResource);
4026 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4027 // Setting last updater and uniqueId
4028 newResource.setContactId(newResource.getContactId().toLowerCase());
4029 newResource.setLastUpdaterUserId(user.getUserId());
4030 newResource.setUniqueId(resourceIdToUpdate);
4031 // Cannot set highest version through UI
4032 newResource.setHighestVersion(currentResource.isHighestVersion());
4033 newResource.setCreationDate(currentResource.getCreationDate());
4035 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4036 newResource, user.getUserId(), inTransaction);
4038 if (processUpdateOfDerivedFrom.isRight()) {
4039 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4040 return Either.right(processUpdateOfDerivedFrom.right().value());
4043 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4044 if (isNotEmpty(newResource.getGroups())) {
4045 for (GroupDefinition group : newResource.getGroups()) {
4046 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4047 groupBusinessLogic.validateAndUpdateGroupMetadata(
4048 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4049 user, newResource.getComponentType(), group, true, false);
4053 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4054 .updateToscaElement(newResource);
4056 if (dataModelResponse.isRight()) {
4057 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4058 componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4059 return Either.right(responseFormat);
4060 } else if (dataModelResponse.left().value() == null) {
4061 log.debug("No response from updateResource");
4062 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4064 return Either.left(dataModelResponse.left().value());
4068 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4069 if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4070 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4072 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4074 newResource.setGroups(updatedGroups);
4078 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4079 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4080 if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4081 String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4082 String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4083 updatedGroup.setName(newGroupName);
4085 return updatedGroup;
4088 * validateResourceFieldsBeforeCreate
4090 * @param user - modifier data (userId)
4091 * @return Either<Boolean , ErrorResponse>
4093 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4094 AuditingActionEnum actionEnum, boolean inTransaction) {
4095 validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4096 // validate category
4097 log.debug("validate category");
4098 validateCategory(user, resource, actionEnum, inTransaction);
4099 // validate vendor name & release & model number
4100 log.debug("validate vendor name");
4101 validateVendorName(user, resource, actionEnum);
4102 log.debug("validate vendor release");
4103 validateVendorReleaseName(user, resource, actionEnum);
4104 log.debug("validate resource vendor model number");
4105 validateResourceVendorModelNumber(user, resource, actionEnum);
4107 log.debug("validate cost");
4108 validateCost(resource);
4109 // validate licenseType
4110 log.debug("validate licenseType");
4111 validateLicenseType(user, resource, actionEnum);
4112 // validate template (derived from)
4113 log.debug("validate derived from");
4114 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4115 resource.setDerivedFrom(null);
4117 validateDerivedFromExist(user, resource, actionEnum);
4118 // warn about non-updatable fields
4119 checkComponentFieldsForOverrideAttempt(resource);
4120 String currentCreatorFullName = resource.getCreatorFullName();
4121 if (currentCreatorFullName != null) {
4122 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4125 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4126 if (currentLastUpdaterFullName != null) {
4127 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4130 Long currentLastUpdateDate = resource.getLastUpdateDate();
4131 if (currentLastUpdateDate != null) {
4132 log.debug("Resource last update date is automatically set and cannot be updated");
4135 Boolean currentAbstract = resource.isAbstract();
4136 if (currentAbstract != null) {
4137 log.debug("Resource abstract is automatically set and cannot be updated");
4140 return Either.left(true);
4144 * validateResourceFieldsBeforeUpdate
4146 * @param currentResource - Resource object to validate
4149 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4150 boolean inTransaction, boolean isNested) {
4151 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4152 warnNonEditableFields(currentResource, updateInfoResource);
4155 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4156 String currentResourceVersion = currentResource.getVersion();
4157 String updatedResourceVersion = updateInfoResource.getVersion();
4159 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4160 log.debug("Resource version is automatically set and cannot be updated");
4163 String currentCreatorUserId = currentResource.getCreatorUserId();
4164 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4166 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4167 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4170 String currentCreatorFullName = currentResource.getCreatorFullName();
4171 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4173 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4174 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4177 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4178 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4180 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4181 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4184 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4185 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4187 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4188 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4191 Long currentCreationDate = currentResource.getCreationDate();
4192 Long updatedCreationDate = updateInfoResource.getCreationDate();
4194 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4195 log.debug("Resource Creation date is automatically set and cannot be updated");
4198 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4199 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4201 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4202 log.debug("Resource last update date is automatically set and cannot be updated");
4205 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4206 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4208 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4209 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4212 Boolean currentAbstract = currentResource.isAbstract();
4213 Boolean updatedAbstract = updateInfoResource.isAbstract();
4215 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4216 log.debug("Resource abstract is automatically set and cannot be updated");
4219 Boolean currentHighestVersion = currentResource.isHighestVersion();
4220 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4222 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4223 log.debug("Resource highest version is automatically set and cannot be updated");
4226 String currentUuid = currentResource.getUUID();
4227 String updatedUuid = updateInfoResource.getUUID();
4229 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4230 log.debug("Resource UUID is automatically set and cannot be updated");
4233 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4234 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4236 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4237 log.debug("Resource Type cannot be updated");
4240 updateInfoResource.setResourceType(currentResource.getResourceType());
4242 String currentInvariantUuid = currentResource.getInvariantUUID();
4243 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4245 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4246 log.debug("Resource invariant UUID is automatically set and cannot be updated");
4247 updateInfoResource.setInvariantUUID(currentInvariantUuid);
4251 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4252 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4253 log.debug("validate resource name before update");
4254 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4255 log.debug("validate description before update");
4256 validateDescriptionAndCleanup(null, updateInfoResource, null);
4257 log.debug("validate icon before update");
4258 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4259 log.debug("validate tags before update");
4260 validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4261 log.debug("validate vendor name before update");
4262 validateVendorName(null, updateInfoResource, null);
4263 log.debug("validate resource vendor model number before update");
4264 validateResourceVendorModelNumber(currentResource, updateInfoResource);
4265 log.debug("validate vendor release before update");
4266 validateVendorReleaseName(null, updateInfoResource, null);
4267 log.debug("validate contact info before update");
4268 validateContactId(null, updateInfoResource, null);
4269 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4270 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4271 log.debug("validate category before update");
4272 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4276 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4277 String resourceNameUpdated = updateInfoResource.getName();
4278 String resourceNameCurrent = currentResource.getName();
4279 if (resourceNameCurrent.equals(resourceNameUpdated)) {
4282 // In case of CVFC type we should support the case of old VF with CVFC
4283 // instances that were created without the "Cvfc" suffix
4284 return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4285 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4288 private String addCvfcSuffixToResourceName(String resourceName) {
4289 return resourceName + "Cvfc";
4292 private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4293 boolean hasBeenCertified, boolean isNested) {
4294 String resourceNameUpdated = updateInfoResource.getName();
4295 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4296 if (isNested || !hasBeenCertified) {
4297 validateComponentName(null, updateInfoResource, null);
4298 validateResourceNameUniqueness(updateInfoResource);
4299 currentResource.setName(resourceNameUpdated);
4300 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4301 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4304 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4305 resourceNameUpdated);
4306 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4311 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4312 String iconUpdated = updateInfoResource.getIcon();
4313 String iconCurrent = currentResource.getIcon();
4314 if (!iconCurrent.equals(iconUpdated)) {
4315 if (!hasBeenCertified) {
4316 validateIcon(null, updateInfoResource, null);
4318 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4319 throw new ComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4324 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4325 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4326 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4327 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4328 validateResourceVendorModelNumber(null, updateInfoResource, null);
4332 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4333 boolean hasBeenCertified, boolean inTransaction) {
4334 validateCategory(null, updateInfoResource, null, inTransaction);
4335 if (hasBeenCertified) {
4336 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4337 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4338 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4339 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4340 if (!currentCategory.getName().equals(updateCategory.getName())
4341 || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4342 log.info("Category {} cannot be updated once the resource has been certified once.",
4343 currentResource.getCategories());
4344 ResponseFormat errorResponse = componentsUtils
4345 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4346 return Either.right(errorResponse);
4349 return Either.left(true);
4352 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4353 Resource updateInfoResource, boolean hasBeenCertified) {
4355 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4356 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4357 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4358 || updatedDerivedFrom.isEmpty()) {
4359 log.trace("Update normative types");
4360 return Either.left(true);
4363 String derivedFromCurrent = currentDerivedFrom.get(0);
4364 String derivedFromUpdated = updatedDerivedFrom.get(0);
4366 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4367 if (!hasBeenCertified) {
4368 validateDerivedFromExist(null, updateInfoResource, null);
4370 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4371 currentResource, updateInfoResource, null);
4373 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4374 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4375 return validateDerivedFromExtending;
4379 // For derived from, we must know whether it was actually changed,
4380 // otherwise we must do no action.
4381 // Due to changes it inflicts on data model (remove artifacts,
4382 // properties...), it's not like a flat field which can be
4383 // overwritten if not changed.
4384 // So we must indicate that derived from is not changed
4385 updateInfoResource.setDerivedFrom(null);
4387 return Either.left(true);
4390 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4391 Resource updateInfoResource, boolean hasBeenCertified) {
4393 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4394 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4395 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4396 || updatedDerivedFrom.isEmpty()) {
4397 log.trace("Update normative types");
4398 return Either.left(true);
4401 String derivedFromCurrent = currentDerivedFrom.get(0);
4402 String derivedFromUpdated = updatedDerivedFrom.get(0);
4404 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4405 if (!hasBeenCertified) {
4406 validateDerivedFromExist(null, updateInfoResource, null);
4408 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4409 currentResource, updateInfoResource, null);
4411 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4412 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4413 return validateDerivedFromExtending;
4417 return Either.left(true);
4420 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
4421 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4424 String templateName = resource.getDerivedFrom().get(0);
4425 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4426 .validateToscaResourceNameExists(templateName);
4427 if (dataModelResponse.isRight()) {
4428 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4429 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4430 log.debug("request to data model failed with error: {}", storageStatus);
4431 ResponseFormat responseFormat = componentsUtils
4432 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4433 log.trace("audit before sending response");
4434 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4435 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4436 } else if (!dataModelResponse.left().value()) {
4437 log.info("resource template with name: {}, does not exists", templateName);
4438 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4439 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4440 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4444 // Tal G for extending inheritance US815447
4445 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4446 Resource updateInfoResource, AuditingActionEnum actionEnum) {
4447 String currentTemplateName = currentResource.getDerivedFrom().get(0);
4448 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4450 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4451 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4452 if (dataModelResponse.isRight()) {
4453 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4454 BeEcompErrorManager.getInstance()
4455 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4456 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4457 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4458 log.trace("audit before sending response");
4459 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4460 return Either.right(responseFormat);
4463 if (!dataModelResponse.left().value()) {
4464 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4465 currentTemplateName);
4466 ResponseFormat responseFormat = componentsUtils
4467 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4468 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4470 return Either.right(responseFormat);
4473 return Either.left(true);
4476 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4477 log.debug("validate resource derivedFrom field");
4478 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4479 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4480 log.info("derived from (template) field is missing for the resource");
4481 ResponseFormat responseFormat = componentsUtils
4482 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4483 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4485 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4489 private void validateResourceNameUniqueness(Resource resource) {
4491 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4492 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4493 resource.getComponentType());
4494 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4495 log.debug("resource with name: {}, already exists", resource.getName());
4496 throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4497 resource.getName());
4498 } else if(resourceOperationResponse.isRight()){
4499 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4500 throw new StorageException(resourceOperationResponse.right().value());
4505 private void validateCategory(User user, Resource resource,
4506 AuditingActionEnum actionEnum, boolean inTransaction) {
4508 List<CategoryDefinition> categories = resource.getCategories();
4509 if (CollectionUtils.isEmpty(categories)) {
4510 log.debug(CATEGORY_IS_EMPTY);
4511 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4512 ComponentTypeEnum.RESOURCE.getValue());
4513 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4514 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4515 ComponentTypeEnum.RESOURCE.getValue());
4517 if (categories.size() > 1) {
4518 log.debug("Must be only one category for resource");
4519 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4521 CategoryDefinition category = categories.get(0);
4522 List<SubCategoryDefinition> subcategories = category.getSubcategories();
4523 if (CollectionUtils.isEmpty(subcategories)) {
4524 log.debug("Missinig subcategory for resource");
4525 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4527 if (subcategories.size() > 1) {
4528 log.debug("Must be only one sub category for resource");
4529 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4532 SubCategoryDefinition subcategory = subcategories.get(0);
4534 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4535 log.debug(CATEGORY_IS_EMPTY);
4536 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4537 ComponentTypeEnum.RESOURCE.getValue());
4538 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4539 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4540 ComponentTypeEnum.RESOURCE.getValue());
4542 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4543 log.debug(CATEGORY_IS_EMPTY);
4544 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4545 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4546 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4547 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4550 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4553 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4554 User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4555 ResponseFormat responseFormat;
4556 if (category != null && subcategory != null) {
4557 log.debug("validating resource category {} against valid categories list", category);
4558 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4559 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4560 if (categories.isRight()) {
4561 log.debug("failed to retrive resource categories from Titan");
4562 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4563 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4564 throw new ComponentException(categories.right().value());
4566 List<CategoryDefinition> categoryList = categories.left().value();
4567 Optional<CategoryDefinition> foundCategory = categoryList.stream()
4568 .filter(cat -> cat.getName().equals(category.getName()))
4570 if(!foundCategory.isPresent()){
4571 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4572 category, categoryList);
4573 failOnInvalidCategory(user, resource, actionEnum);
4575 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4578 .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4580 if(!foundSubcategory.isPresent()){
4581 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4582 subcategory, foundCategory.get().getSubcategories());
4583 failOnInvalidCategory(user, resource, actionEnum);
4588 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4589 ResponseFormat responseFormat;
4590 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4591 ComponentTypeEnum.RESOURCE.getValue());
4592 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4593 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4594 ComponentTypeEnum.RESOURCE.getValue());
4597 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4598 String vendorRelease = resource.getVendorRelease();
4599 log.debug("validate vendor relese name");
4600 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4601 log.info("vendor relese name is missing.");
4602 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4603 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4604 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4607 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4610 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4611 if (vendorRelease != null) {
4612 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4613 log.info("vendor release exceds limit.");
4614 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4615 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4616 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4617 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4620 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4621 log.info("vendor release is not valid.");
4622 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4623 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4624 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4629 private void validateVendorName(User user, Resource resource,
4630 AuditingActionEnum actionEnum) {
4631 String vendorName = resource.getVendorName();
4632 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4633 log.info("vendor name is missing.");
4634 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4635 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4636 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
4638 validateVendorName(vendorName, user, resource, actionEnum);
4641 private void validateVendorName(String vendorName, User user, Resource resource,
4642 AuditingActionEnum actionEnum) {
4643 if (vendorName != null) {
4644 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4645 log.info("vendor name exceds limit.");
4646 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4647 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4648 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4649 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4650 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4653 if (!ValidationUtils.validateVendorName(vendorName)) {
4654 log.info("vendor name is not valid.");
4655 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4656 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4657 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
4662 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4663 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4664 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4665 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4666 log.info("resource vendor model number exceeds limit.");
4667 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4668 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4669 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4670 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4671 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4672 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4674 // resource vendor model number is currently validated as vendor
4676 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4677 log.info("resource vendor model number is not valid.");
4678 ResponseFormat errorResponse = componentsUtils
4679 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4680 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4681 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4687 private void validateCost(Resource resource) {
4688 String cost = resource.getCost();
4690 if (!ValidationUtils.validateCost(cost)) {
4691 log.debug("resource cost is invalid.");
4692 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4697 private void validateLicenseType(User user, Resource resource,
4698 AuditingActionEnum actionEnum) {
4699 log.debug("validate licenseType");
4700 String licenseType = resource.getLicenseType();
4701 if (licenseType != null) {
4702 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4704 if (!licenseTypes.contains(licenseType)) {
4705 log.debug("License type {} isn't configured", licenseType);
4706 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4707 if (actionEnum != null) {
4708 // In update case, no audit is required
4709 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4711 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4716 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4717 Resource updatedResource, String userId, boolean inTransaction) {
4718 Either<Operation, ResponseFormat> deleteArtifactByInterface;
4719 if (updatedResource.getDerivedFrom() != null) {
4720 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4721 log.debug("1. Removing interface artifacts from graph");
4722 // Remove all interface artifacts of resource
4723 String resourceId = updatedResource.getUniqueId();
4724 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4726 if (interfaces != null) {
4727 Collection<InterfaceDefinition> values = interfaces.values();
4728 for (InterfaceDefinition interfaceDefinition : values) {
4729 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4731 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4732 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4733 if (operations != null) {
4734 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4735 Operation operation = operationEntry.getValue();
4736 ArtifactDefinition implementation = operation.getImplementationArtifact();
4737 if (implementation != null) {
4738 String uniqueId = implementation.getUniqueId();
4739 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4740 uniqueId, operationEntry.getKey(), interfaceType);
4741 // only thing that transacts and locks here
4742 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4745 if (deleteArtifactByInterface.isRight()) {
4746 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4747 if (!inTransaction) {
4748 titanDao.rollback();
4750 return Either.right(deleteArtifactByInterface.right().value());
4753 log.trace("No implementation found for operation {} - nothing to delete",
4754 operationEntry.getKey());
4758 log.trace("No operations found for interface type {}", interfaceType);
4762 log.debug("2. Removing properties");
4763 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4764 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4766 if (findPropertiesOfNode.isRight()
4767 && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4768 log.debug("Failed to remove all properties of resource");
4769 if (!inTransaction) {
4770 titanDao.rollback();
4772 return Either.right(componentsUtils.getResponseFormat(
4773 componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4777 log.debug("Derived from wasn't changed during update");
4780 if (inTransaction) {
4781 return Either.left(true);
4784 return Either.left(true);
4788 /**** Auditing *******************/
4790 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4791 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4792 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4794 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4796 return webApplicationContext.getBean(class1);
4799 public ICapabilityTypeOperation getCapabilityTypeOperation() {
4800 return capabilityTypeOperation;
4803 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4804 this.capabilityTypeOperation = capabilityTypeOperation;
4807 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4808 log.debug("validate resource properties default values");
4809 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4810 List<PropertyDefinition> properties = resource.getProperties();
4811 if (properties != null) {
4812 eitherResult = iterateOverProperties(properties);
4814 return eitherResult;
4817 public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4818 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4820 String innerType = null;
4821 for (PropertyDefinition property : properties) {
4822 if (!propertyOperation.isPropertyTypeValid(property)) {
4823 log.info("Invalid type for property {}", property);
4824 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4825 ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4826 eitherResult = Either.right(responseFormat);
4830 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4831 applicationDataTypeCache);
4832 if (allDataTypes.isRight()) {
4833 return Either.right(allDataTypes.right().value());
4836 type = property.getType();
4838 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4839 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4840 if(responseFormat != null) {
4844 eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4846 return eitherResult;
4849 private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4850 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4851 log.info("Invalid default value for property {}", property);
4852 ResponseFormat responseFormat;
4853 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4854 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4855 property.getName(), type, innerType, property.getDefaultValue());
4857 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4858 property.getName(), type, property.getDefaultValue());
4860 return Either.right(responseFormat);
4863 return Either.left(true);
4866 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4867 ResponseFormat responseFormat = null;
4868 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4869 .isPropertyInnerTypeValid(property, allDataTypes);
4870 innerType = propertyInnerTypeValid.getLeft();
4871 if (!propertyInnerTypeValid.getRight().booleanValue()) {
4872 log.info("Invalid inner type for property {}", property);
4873 responseFormat = componentsUtils.getResponseFormat(
4874 ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4876 return responseFormat;
4880 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4881 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4885 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4886 return componentInstanceBusinessLogic;
4889 private String getComponentTypeForResponse(Component component) {
4890 String componentTypeForResponse = "SERVICE";
4891 if (component instanceof Resource) {
4892 componentTypeForResponse = ((Resource) component).getResourceType().name();
4894 return componentTypeForResponse;
4897 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4900 validateUserExists(user, "Get resource from csar UUID",
4903 // get resource from csar uuid
4904 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4905 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4906 if (either.isRight()) {
4907 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4909 return Either.right(resp);
4912 return Either.left(either.left().value());
4916 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
4917 String componentId, String userId) {
4921 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
4922 String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
4923 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4925 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
4926 uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
4927 return validCapabilitiesMap;
4930 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
4931 String capabilityType = capabilities.get(0).getType();
4932 if (defaultCapabilities.containsKey(capabilityType)) {
4933 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
4934 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
4935 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
4936 validCapabilityList.add(defaultCapability);
4937 validCapabilitiesMap.put(key, validCapabilityList);
4939 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
4943 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
4944 if (CollectionUtils.isEmpty(defaultCapability.getProperties())
4945 && isNotEmpty(capabilities.get(0).getProperties())) {
4946 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
4947 defaultCapability.getName(), resourceId);
4949 "Failed to update capability property values. Property list of fetched capability {} is empty. ",
4950 defaultCapability.getName());
4951 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
4952 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
4953 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
4957 private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
4958 CapabilityDefinition defaultCapability;
4959 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
4960 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
4962 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
4963 .getToscaFullElement(resourceId);
4964 if (getFullComponentRes.isRight()) {
4965 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
4966 getFullComponentRes.right().value());
4967 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
4970 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
4972 return defaultCapability;
4975 private void validateUniquenessUpdateUploadedComponentInstanceCapability(
4976 CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
4977 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
4978 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
4979 .collect(toMap(PropertyDefinition::getName, Function.identity()));
4980 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
4981 for (UploadPropInfo property : uploadedProperties) {
4982 String propertyName = property.getName().toLowerCase();
4983 String propertyType = property.getType();
4984 ComponentInstanceProperty validProperty;
4985 if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
4986 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
4989 validProperty = new ComponentInstanceProperty();
4990 validProperty.setName(propertyName);
4991 if (property.getValue() != null) {
4992 validProperty.setValue(property.getValue().toString());
4994 validProperty.setDescription(property.getDescription());
4995 validProperty.setPassword(property.isPassword());
4996 validProperties.add(validProperty);
4998 defaultCapability.setProperties(validProperties);
5001 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
5002 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
5005 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
5006 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
5007 Resource resource, User user) {
5009 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
5010 ArtifactOperationEnum.class);
5011 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
5012 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
5013 .left(nodeTypeArtifactsToHandle);
5015 // add all found Csar artifacts to list to upload
5016 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
5017 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
5018 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
5019 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5020 ArtifactDefinition foundArtifact;
5022 if (!existingArtifactsToHandle.isEmpty()) {
5023 foundArtifact = existingArtifactsToHandle.stream()
5024 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5026 if (foundArtifact != null) {
5027 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5028 .getArtifactType()) {
5029 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5030 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5031 // if current artifact already exists, but has
5032 // different content, add him to the list to
5034 artifactsToUpdate.add(currNewArtifact);
5036 // remove found artifact from the list of existing
5037 // artifacts to handle, because it was already
5039 existingArtifactsToHandle.remove(foundArtifact);
5040 // and remove found artifact from the list to
5041 // upload, because it should either be updated or be
5043 artifactsToUpload.remove(currNewArtifact);
5045 log.debug("Can't upload two artifact with the same name {}.",
5046 currNewArtifact.getArtifactName());
5047 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5048 ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5049 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5050 foundArtifact.getArtifactType());
5051 AuditingActionEnum auditingAction = artifactsBusinessLogic
5052 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5053 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5054 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5055 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5056 resource.getComponentType(), null);
5057 responseWrapper.setInnerElement(responseFormat);
5063 if (responseWrapper.isEmpty()) {
5064 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5065 if (currArtifact.getIsFromCsar()) {
5066 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5068 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5073 if (responseWrapper.isEmpty()) {
5074 if (!artifactsToUpload.isEmpty()) {
5075 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5077 if (!artifactsToUpdate.isEmpty()) {
5078 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5080 if (!artifactsToDelete.isEmpty()) {
5081 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5084 if (!responseWrapper.isEmpty()) {
5085 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5087 } catch (Exception e) {
5088 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5089 responseWrapper.setInnerElement(responseFormat);
5090 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5092 return nodeTypeArtifactsToHandleRes;
5095 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5096 String nodeTypeFullName) {
5098 String actualVfName;
5099 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5100 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5101 actualType = ResourceTypeEnum.VFC.name();
5103 actualVfName = vfResourceName;
5104 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())
5128 public ICacheMangerOperation getCacheManagerOperation() {
5129 return cacheManagerOperation;
5132 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
5133 this.cacheManagerOperation = cacheManagerOperation;
5137 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
5139 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5140 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
5143 if (resourceResultEither.isRight()) {
5144 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5145 log.debug("Failed to found resource with id {} ", resourceId);
5146 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5149 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5150 return Either.right(componentsUtils.getResponseFormatByResource(
5151 componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5154 Resource resource = resourceResultEither.left().value();
5155 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5156 dataParamsToReturn);
5157 return Either.left(dataTransfer);
5161 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5162 Resource resource = (Resource) clonedComponent;
5163 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5164 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5165 .shouldUpgradeToLatestDerived(resource);
5166 if (shouldUpgradeToLatestDerived.isRight()) {
5167 return Either.right(
5168 componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5170 return Either.left(shouldUpgradeToLatestDerived.left().value());
5172 return super.shouldUpgradeToLatestDerived(clonedComponent);
5176 private Either<Boolean, ResponseFormat> validateAndUpdateInterfaces(String resourceId, Resource resourceUpdate) {
5177 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
5178 toscaOperationFacade.getToscaElement(resourceId);
5179 if (resourceStorageOperationStatusEither.isRight()) {
5180 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
5181 log.error("Failed to fetch resource information by resource id {}, error {}", resourceId, errorStatus);
5182 return Either.right(componentsUtils
5183 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5186 Resource storedResource = resourceStorageOperationStatusEither.left().value();
5187 Map<String, InterfaceDefinition> storedResourceInterfaces = storedResource.getInterfaces();
5189 if(!storedResource.getName().equals(resourceUpdate.getName()) ) {
5190 Collection<InterfaceDefinition> interfaceDefinitionListFromToscaName = InterfaceUtils
5191 .getInterfaceDefinitionListFromToscaName(storedResource.getInterfaces().values(),
5192 storedResource.getName());
5194 for (InterfaceDefinition interfaceDefinition : storedResourceInterfaces.values()) {
5195 Either<InterfaceDefinition, ResponseFormat> updateInterfaceDefinitionEither = updateInterfaceDefinition(resourceUpdate,
5196 interfaceDefinition,
5197 interfaceDefinitionListFromToscaName);
5198 if(updateInterfaceDefinitionEither.isRight()) {
5199 return Either.right(updateInterfaceDefinitionEither.right().value());
5204 return Either.left(Boolean.TRUE);
5207 private Either<InterfaceDefinition, ResponseFormat > updateInterfaceDefinition(Resource resourceUpdate,
5208 InterfaceDefinition interfaceDefinition,
5209 Collection<InterfaceDefinition> interfaceDefinitionListFromToscaName) {
5210 interfaceDefinitionListFromToscaName.forEach(interfaceDefinitionFromList -> {
5211 if(interfaceDefinitionFromList.getToscaResourceName().equals(interfaceDefinition.getToscaResourceName())) {
5212 log.info("Going to Update interface definition toscaResourceName {} to {}",
5213 interfaceDefinitionFromList.getToscaResourceName(),
5214 InterfaceUtils.createInterfaceToscaResourceName(resourceUpdate.getName()));
5215 interfaceDefinition.setToscaResourceName(InterfaceUtils
5216 .createInterfaceToscaResourceName(resourceUpdate.getName()));
5220 Either<InterfaceDefinition, StorageOperationStatus> interfaceUpdate = interfaceOperation
5221 .updateInterface(resourceUpdate.getUniqueId(), interfaceDefinition);
5222 if (interfaceUpdate.isRight()) {
5223 log.error("Failed to Update interface {}. Response is {}. ", resourceUpdate.getName(), interfaceUpdate.right().value());
5224 titanDao.rollback();
5225 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(interfaceUpdate.right().value(), ComponentTypeEnum.RESOURCE)));
5227 } catch (Exception e) {
5228 log.error("Exception occurred during update interface toscaResourceName : {}", e);
5229 titanDao.rollback();
5230 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5233 return Either.left( interfaceDefinition);