2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
24 import fj.data.Either;
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.collections.MapUtils;
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.commons.lang3.tuple.ImmutablePair;
30 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
31 import org.openecomp.sdc.be.components.csar.CsarBusinessLogic;
32 import org.openecomp.sdc.be.components.csar.CsarInfo;
33 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
34 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
36 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
37 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
39 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
40 import org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic;
41 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
42 import org.openecomp.sdc.be.config.BeEcompErrorManager;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
44 import org.openecomp.sdc.be.config.ConfigurationManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
47 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
48 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
49 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
50 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.CreatedFrom;
57 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
59 import org.openecomp.sdc.be.impl.ComponentsUtils;
60 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
61 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
62 import org.openecomp.sdc.be.model.*;
63 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
64 import org.openecomp.sdc.be.model.category.CategoryDefinition;
65 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
66 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
67 import org.openecomp.sdc.be.model.operations.StorageException;
68 import org.openecomp.sdc.be.model.operations.api.*;
69 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
70 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
71 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
72 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
73 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
74 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
75 import org.openecomp.sdc.be.tosca.CsarUtils;
76 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
77 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
78 import org.openecomp.sdc.be.user.IUserBusinessLogic;
79 import org.openecomp.sdc.be.user.UserBusinessLogic;
80 import org.openecomp.sdc.be.utils.CommonBeUtils;
81 import org.openecomp.sdc.be.utils.TypeUtils;
82 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
83 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
84 import org.openecomp.sdc.common.api.Constants;
85 import org.openecomp.sdc.common.datastructure.Wrapper;
86 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
87 import org.openecomp.sdc.common.log.wrappers.Logger;
88 import org.openecomp.sdc.common.util.GeneralUtility;
89 import org.openecomp.sdc.common.util.ValidationUtils;
90 import org.openecomp.sdc.exception.ResponseFormat;
91 import org.springframework.beans.factory.annotation.Autowired;
92 import org.springframework.web.context.WebApplicationContext;
93 import org.yaml.snakeyaml.DumperOptions;
94 import org.yaml.snakeyaml.Yaml;
96 import javax.servlet.ServletContext;
98 import java.util.Map.Entry;
99 import java.util.function.Function;
100 import java.util.regex.Pattern;
102 import static java.util.stream.Collectors.*;
103 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
104 import static org.apache.commons.collections.MapUtils.isEmpty;
105 import static org.apache.commons.collections.MapUtils.isNotEmpty;
106 import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
107 import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
108 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
110 @org.springframework.stereotype.Component("resourceBusinessLogic")
111 public class ResourceBusinessLogic extends ComponentBusinessLogic {
113 private static final String DELETE_RESOURCE = "Delete Resource";
114 private static final String IN_RESOURCE = " in resource {} ";
115 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
116 public static final String INITIAL_VERSION = "0.1";
117 private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
118 private static final String CERTIFICATION_ON_IMPORT = "certification on import";
119 private static final String CREATE_RESOURCE = "Create Resource";
120 private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
121 private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
122 private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
123 private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
124 private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {} in resource {} ";
127 * Default constructor
129 public ResourceBusinessLogic() {
130 log.debug("ResourceBusinessLogic started");
134 private ICapabilityTypeOperation capabilityTypeOperation = null;
137 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
140 private LifecycleBusinessLogic lifecycleBusinessLogic;
143 private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
146 private ResourceImportManager resourceImportManager;
149 private InputsBusinessLogic inputsBusinessLogic;
152 private CompositionBusinessLogic compositionBusinessLogic;
155 private ICacheMangerOperation cacheManagerOperation;
158 private ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
161 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
164 private MergeInstanceUtils mergeInstanceUtils;
167 private UiComponentDataConverter uiComponentDataConverter;
170 private CsarBusinessLogic csarBusinessLogic;
172 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
173 return lifecycleBusinessLogic;
176 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
177 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
180 public IElementOperation getElementDao() {
184 public void setElementDao(IElementOperation elementDao) {
185 this.elementDao = elementDao;
188 public IUserBusinessLogic getUserAdmin() {
189 return this.userAdmin;
192 public void setUserAdmin(UserBusinessLogic userAdmin) {
193 this.userAdmin = userAdmin;
196 public ComponentsUtils getComponentsUtils() {
197 return this.componentsUtils;
200 public void setComponentsUtils(ComponentsUtils componentsUtils) {
201 this.componentsUtils = componentsUtils;
204 public ArtifactsBusinessLogic getArtifactsManager() {
205 return artifactsBusinessLogic;
208 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
209 this.artifactsBusinessLogic = artifactsManager;
212 public ApplicationDataTypeCache getApplicationDataTypeCache() {
213 return applicationDataTypeCache;
216 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
217 this.applicationDataTypeCache = applicationDataTypeCache;
221 * the method returns a list of all the resources that are certified, the
222 * returned resources are only abstract or only none abstract according to
229 public List<Resource> getAllCertifiedResources(boolean getAbstract,
230 HighestFilterEnum highestFilter, String userId) {
231 User user = validateUserExists(userId, "get All Certified Resources", false);
232 Boolean isHighest = null;
233 switch (highestFilter) {
239 case NON_HIGHEST_ONLY:
245 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
246 .getAllCertifiedResources(getAbstract, isHighest);
248 if (getResponse.isRight()) {
249 throw new StorageException(getResponse.right().value());
252 return getResponse.left().value();
255 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
256 ResourceTypeEnum resourceTypeEnum, String userId) {
258 validateUserExists(userId, "validate Resource Name Exists", false);
260 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
261 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
265 if (dataModelResponse.isLeft()) {
266 Map<String, Boolean> result = new HashMap<>();
267 result.put("isValid", dataModelResponse.left().value());
268 log.debug("validation was successfully performed.");
269 return Either.left(result);
272 ResponseFormat responseFormat = componentsUtils
273 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
275 return Either.right(responseFormat);
278 public Resource createResource(Resource resource, AuditingActionEnum auditingAction,
279 User user, Map<String, byte[]> csarUIPayload, String payloadName) {
280 validateResourceBeforeCreate(resource, user, false);
281 String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
282 if (StringUtils.isNotEmpty(csarUUID)) {
283 csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
284 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
285 return createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
288 return createResourceByDao(resource, user, auditingAction, false, false);
291 public Resource validateAndUpdateResourceFromCsar(Resource resource, User user,
292 Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
293 String csarUUID = payloadName;
294 String csarVersion = null;
295 Resource updatedResource = null;
296 if (payloadName == null) {
297 csarUUID = resource.getCsarUUID();
298 csarVersion = resource.getCsarVersion();
300 if (csarUUID != null && !csarUUID.isEmpty()) {
301 Resource oldResource = getResourceByUniqueId(resourceUniqueId);
302 validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
303 validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
304 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
305 overrideImmutableMetadata(oldResource, resource);
307 validateResourceBeforeCreate(resource, user, false);
308 String oldCsarVersion = oldResource.getCsarVersion();
309 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
311 // (on boarding flow): If the update includes same csarUUID and
312 // same csarVersion as already in the VF - no need to import the
313 // csar (do only metadata changes if there are).
314 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
315 updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
318 updatedResource = updateResourceFromCsar(oldResource, resource, user,
319 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
322 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
323 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
325 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
326 throw new ComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
328 return updatedResource;
331 private void validateCsarIsNotAlreadyUsed(Resource oldResource,
332 Resource resource, String csarUUID, User user) {
333 // (on boarding flow): If the update includes a csarUUID: verify this
334 // csarUUID is not in use by another VF, If it is - use same error as
336 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
337 // select another or update the existing VF." %1 - csarUUID, %2 - VF
339 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
340 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
341 if (resourceLinkedToCsarRes.isRight()) {
342 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
343 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
344 resource.getSystemName());
345 throw new StorageException(resourceLinkedToCsarRes.right().value());
347 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
348 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
349 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
350 resourceLinkedToCsarRes.left().value().getName());
351 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
352 throw new ComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
353 resourceLinkedToCsarRes.left().value().getName());
357 private void validateCsarUuidMatching(Resource resource,
358 Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
359 // (on boarding flow): If the update includes csarUUID which is
360 // different from the csarUUID of the VF - fail with
361 // error: "Error: Resource %1 cannot be updated using since it is linked
362 // to a different VSP" %1 - VF name
363 String oldCsarUUID = oldResource.getCsarUUID();
364 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
366 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
367 resourceUniqueId, csarUUID, oldCsarUUID);
368 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
369 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
370 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
371 throw new ComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
375 private Resource getResourceByUniqueId(String resourceUniqueId) {
376 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
377 if (oldResourceRes.isRight()) {
378 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
379 oldResourceRes.right().value());
380 throw new StorageException(oldResourceRes.right().value());
382 return oldResourceRes.left().value();
385 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
386 resource.setName(oldRresource.getName());
387 resource.setIcon(oldRresource.getIcon());
388 resource.setTags(oldRresource.getTags());
389 resource.setCategories(oldRresource.getCategories());
390 resource.setDerivedFrom(oldRresource.getDerivedFrom());
393 private Resource updateResourceFromCsar(Resource oldResource, Resource newResource,
394 User user, AuditingActionEnum updateResource, boolean inTransaction,
395 Map<String, byte[]> csarUIPayload, String csarUUID) {
396 Resource updatedResource = null;
397 validateLifecycleState(oldResource, user);
398 String lockedResourceId = oldResource.getUniqueId();
399 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
400 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
401 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
402 "update Resource From Csar");
403 if (lockResult.isRight()) {
404 throw new ComponentException(lockResult.right().value());
407 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
409 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
410 nodeTypesInfo, csarInfo, oldResource);
411 if (findNodeTypesArtifactsToHandleRes.isRight()) {
412 log.debug("failed to find node types for update with artifacts during import csar {}. ",
413 csarInfo.getCsarUUID());
414 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
416 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
419 updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
420 csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
422 connectUiRelations(oldResource, updatedResource);
424 } catch (ComponentException|StorageException e){
425 rollback(inTransaction, newResource, createdArtifacts, null);
430 log.debug("unlock resource {}", lockedResourceId);
431 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
433 return updatedResource;
437 private void validateLifecycleState(Resource oldResource, User user) {
438 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldResource.getLifecycleState()) &&
439 !oldResource.getLastUpdaterUserId().equals(user.getUserId())) {
440 log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
441 oldResource.getLastUpdaterUserId(), user.getUserId());
442 throw new ComponentException(ActionStatus.RESTRICTED_OPERATION);
446 private Either<Resource, ResponseFormat> connectUiRelations(Resource oldResource, Resource newResource) {
447 Either<Resource, ResponseFormat> result;
449 List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.updateUiRelationsInResource(oldResource, newResource);
451 StorageOperationStatus status = toscaOperationFacade.associateResourceInstances(newResource.getUniqueId(), updatedUiRelations);
452 if (status == StorageOperationStatus.OK) {
453 newResource.getComponentInstancesRelations().addAll(updatedUiRelations);
454 result = Either.left(newResource);
456 result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), newResource));
462 private Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
463 AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
464 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
465 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
466 String nodeName, boolean isNested) {
467 boolean inTransaction = true;
468 boolean shouldLock = false;
469 Resource preparedResource = null;
470 ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null;
472 uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName);
473 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
474 preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
475 inTransaction, shouldLock, isNested).left;
476 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
477 handleResourceGenericType(preparedResource);
478 handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
479 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
480 preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
481 preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
482 preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
483 } catch (ComponentException e) {
484 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
485 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
486 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
488 } catch (StorageException e){
489 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
490 log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat);
491 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum);
494 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
495 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
496 preparedResource.getSystemName());
497 if (validateUpdateVfGroupNamesRes.isRight()) {
499 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
501 // add groups to resource
502 Map<String, GroupDefinition> groups;
504 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
505 groups = validateUpdateVfGroupNamesRes.left().value();
507 groups = uploadComponentInstanceInfoMap.getGroups();
509 handleGroupsProperties(preparedResource, groups);
510 preparedResource = updateGroupsOnResource(preparedResource, groups);
511 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
512 nodeTypesArtifactsToHandle);
514 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
515 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
516 if (updateArtifactsEither.isRight()) {
517 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
518 throw new ComponentException(updateArtifactsEither.right().value());
520 preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
522 ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
523 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
524 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
526 throw new ComponentException(responseFormat);
528 compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
529 return preparedResource;
532 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
533 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
534 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
536 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
537 Resource resource = preparedResource;
539 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
540 .getNodeTypesArtifactsToHandle();
541 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
542 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
543 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
544 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
545 if (handleNodeTypeArtifactsRes.isRight()) {
546 return Either.right(handleNodeTypeArtifactsRes.right().value());
550 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
551 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
552 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
553 if (createdCsarArtifactsEither.isRight()) {
554 return createdCsarArtifactsEither;
557 resource = createdCsarArtifactsEither.left().value();
559 return Either.left(resource);
562 private Resource handleResourceGenericType(Resource resource) {
563 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
564 if (resource.shouldGenerateInputs()) {
565 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
567 return genericResource;
570 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
571 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
573 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
574 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
575 = Either.left(nodeTypesArtifactsToHandle);
578 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
579 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
580 extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
581 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
582 oldResource.getName(), csarInfo.getCsarUUID());
583 extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
584 extractedVfcsArtifacts,
585 namespace, vfcToscaNames));
586 } catch (Exception e) {
587 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
588 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
589 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
591 return nodeTypesArtifactsToHandleRes;
594 private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
595 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace, ImmutablePair<String, String> vfcToscaNames){
597 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
598 log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
599 Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
600 if (!isEmpty(extractedVfcsArtifacts)) {
601 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
602 if (extractedVfcsArtifacts.containsKey(namespace)) {
603 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
605 curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
606 } else if (curNodeType != null) {
607 // delete all artifacts if have not received artifacts from
609 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
610 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
611 // delete all informational artifacts
612 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
613 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
615 // delete all deployment artifacts
616 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
617 if (!artifactsToDelete.isEmpty()) {
618 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
621 if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
622 nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
626 private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName, StorageOperationStatus status) {
627 if (status != null && status != StorageOperationStatus.NOT_FOUND) {
628 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
629 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
630 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
631 throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
632 } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
633 return (Resource)toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
635 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
640 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
641 Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
643 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
645 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
646 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
647 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
648 processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
649 collectExistingArtifacts(curNodeType));
650 nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
651 } catch (Exception e) {
652 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
653 throw new ComponentException(ActionStatus.GENERAL_ERROR);
655 return nodeTypeArtifactsToHandle;
658 private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
659 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
660 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
661 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
662 if (!artifactsToUpload.isEmpty()) {
663 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
665 if (!artifactsToUpdate.isEmpty()) {
666 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
668 if (!artifactsToDelete.isEmpty()) {
669 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
672 return nodeTypeArtifactsToHandle;
675 private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
676 List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
677 Map<String, ArtifactDefinition> existingArtifacts) {
678 if (!existingArtifacts.isEmpty()) {
679 extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
680 artifactsToDelete.addAll(existingArtifacts.values());
684 private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
685 Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
687 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
689 if (foundArtifact.isPresent()) {
690 if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
691 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
692 existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
693 artifactsToUpload.remove(currNewArtifact);
695 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
696 throw new ComponentException(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
697 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
698 foundArtifact.get().getArtifactType());
703 private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact, ArtifactDefinition foundArtifact) {
704 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
705 foundArtifact.setPayload(currNewArtifact.getPayloadData());
706 foundArtifact.setPayloadData(
707 Base64.encodeBase64String(currNewArtifact.getPayloadData()));
708 foundArtifact.setArtifactChecksum(GeneralUtility
709 .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
710 artifactsToUpdate.add(foundArtifact);
714 private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
715 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
716 if (curNodeType == null) {
717 return existingArtifacts;
719 if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
720 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
722 if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
724 .putAll(curNodeType.getArtifacts().entrySet()
726 .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
727 .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
729 return existingArtifacts;
733 * Changes resource life cycle state to checked out
737 * @param inTransaction
740 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
741 Either<Resource, ResponseFormat> checkoutResourceRes;
743 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
744 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
746 "************* Going to change life cycle state of resource {} to not certified checked out. ",
748 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
749 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
750 new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
751 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
752 inTransaction, true);
753 if (checkoutRes.isRight()) {
754 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
755 resource.getComponentType().getNodeType(), resource.getUniqueId(),
756 checkoutRes.right().value().getStatus());
757 checkoutResourceRes = Either.right(checkoutRes.right().value());
759 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
762 checkoutResourceRes = Either.left(resource);
764 } catch (Exception e) {
765 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
766 checkoutResourceRes = Either.right(responseFormat);
767 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
770 return checkoutResourceRes;
774 * Handles Artifacts of NodeType
776 * @param nodeTypeResource
777 * @param nodeTypeArtifactsToHandle
779 * @param inTransaction
782 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
783 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
784 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
785 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
786 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
787 Either<Resource, ResponseFormat> changeStateResponse;
789 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
790 if (changeStateResponse.isRight()) {
791 return Either.right(changeStateResponse.right().value());
793 nodeTypeResource = changeStateResponse.left().value();
795 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
796 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
797 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
799 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
800 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
801 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
802 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
803 nodeTypeResource.getName());
804 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
805 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
806 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
807 ignoreLifecycleState, curOperation),
808 false, inTransaction);
809 if (handleNodeTypeArtifactsRequestRes.isRight()) {
810 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
813 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
814 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
816 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
819 if (handleNodeTypeArtifactsRes == null) {
820 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
822 } catch (Exception e) {
823 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
824 handleNodeTypeArtifactsRes = Either.right(responseFormat);
825 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
827 return handleNodeTypeArtifactsRes;
830 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
831 String vfResourceName, CsarInfo csarInfo) {
832 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
834 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
835 if (!nodes.isEmpty()) {
836 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
837 while (nodesNameEntry.hasNext()) {
838 Entry<String, Object> nodeType = nodesNameEntry.next();
839 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
840 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
841 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
844 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
845 vfcToscaNames.put(cvfc.getType(),
846 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
848 return vfcToscaNames;
851 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
852 Map<String, Object> nodes = new HashMap<>();
853 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
854 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
856 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
860 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
861 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
862 .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
863 if (eitherNodeTypes.isLeft()) {
864 nodes.putAll(eitherNodeTypes.left().value());
868 public Resource createResourceFromCsar(Resource resource, User user,
869 Map<String, byte[]> csarUIPayload, String csarUUID) {
870 log.trace("************* created successfully from YAML, resource TOSCA ");
872 CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
874 Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
875 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
876 nodeTypesInfo, csarInfo, resource);
877 if (findNodeTypesArtifactsToHandleRes.isRight()) {
878 log.debug("failed to find node types for update with artifacts during import csar {}. ",
879 csarInfo.getCsarUUID());
880 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
882 Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
883 nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
885 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
886 vfResource.getToscaResourceName());
890 private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
891 log.trace("validating resource before create");
892 user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
893 // validate user role
894 validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
895 // VF / PNF "derivedFrom" should be null (or ignored)
896 if (ModelConverter.isAtomicComponent(resource)) {
897 validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
899 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
903 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
904 // nodeTypesArtifactsToCreate, true, false, null
905 private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
906 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
907 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
908 boolean shouldLock, boolean inTransaction, String nodeName) {
910 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
911 Resource createdResource;
913 ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName);
914 log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
915 createdResource = createResourceAndRIsFromYaml(yamlName, resource,
916 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
917 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
918 log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
919 } catch (ComponentException e) {
920 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
921 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
923 } catch (StorageException e){
924 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
925 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
928 return createdResource;
932 public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
933 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
934 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
937 Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
938 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
939 if (toscaVersion.isRight()) {
940 throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
942 Map<String, Object> mapToConvert = new HashMap<>();
943 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
944 Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
945 createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
946 return csarInfo.getCreatedNodes();
949 private Map<String,Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
950 return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
951 .left().orValue(HashMap::new);
954 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) {
955 Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
956 Resource vfcCreated = null;
957 while (nodesNameValueIter.hasNext()) {
958 Entry<String, Object> nodeType = nodesNameValueIter.next();
959 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
960 || nodeTypesArtifactsToHandle.isEmpty() ? null
961 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
963 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
964 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
965 vfcCreated = handleNestedVfc(resource,
966 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
968 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
969 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
970 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
971 log.trace("************* Going to create node {}", nodeType.getKey());
972 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
973 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
975 log.debug("************* Finished to create node {}", nodeType.getKey());
977 vfcCreated = resourceCreated.getLeft();
978 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
979 vfcCreated.getToscaResourceName());
981 if (vfcCreated != null) {
982 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
984 mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
988 private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
989 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
992 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
993 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
995 log.debug("************* Going to create node types from yaml {}", yamlName);
996 createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
997 nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
998 log.debug("************* Finished to create node types from yaml {}", yamlName);
1000 if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1001 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1002 resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1003 csarInfo, nodeName, yamlName);
1008 private Resource handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1009 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1010 String nodeName, String yamlName) {
1012 Resource oldComplexVfc = null;
1013 Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1014 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1015 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1016 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1017 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1018 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1019 nodeName).getRight());
1021 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1022 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1023 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1024 throw new ComponentException(ActionStatus.GENERAL_ERROR);
1025 } else if (oldComplexVfcRes.isLeft()) {
1026 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
1027 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1028 oldComplexVfcRes.left().value(), newComplexVfc,
1029 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1030 if (eitherValidation.isLeft()) {
1031 oldComplexVfc = oldComplexVfcRes.left().value();
1034 newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1035 oldComplexVfc, newComplexVfc);
1036 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1037 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1038 CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1039 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1040 Either<Resource, ResponseFormat> result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1042 if (result.isRight()) {
1043 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1045 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1046 csarInfo.removeNodeFromQueue();
1047 return result.left().value();
1050 private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1051 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1052 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1054 Resource handleComplexVfcRes;
1055 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1056 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1057 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1058 .collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
1059 CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1060 if (oldComplexVfc == null) {
1061 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1062 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1064 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1065 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1066 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1068 return handleComplexVfcRes;
1071 private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1072 Map<String, NodeTypeInfo> nodesInfo) {
1074 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1075 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1076 csarInfo.addNodeToQueue(nodeName);
1077 return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1078 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1081 private String getNodeTypeActualName(String fullName) {
1082 String nameWithouNamespacePrefix = fullName
1083 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1084 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1085 String resourceType = findTypes[0];
1086 return nameWithouNamespacePrefix.substring(resourceType.length());
1089 private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
1090 String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1091 Resource resourceVf, boolean needLock,
1092 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1093 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1096 UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1098 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1099 resourceMetaData.getResourceType(), csarInfo);
1100 user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1101 return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
1102 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1103 nodeNameValue.getKey(), isNested);
1106 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1107 String nodeResourceType, CsarInfo csarInfo) {
1108 // We need to create a Yaml from each node_types in order to create
1109 // resource from each node type using import normative flow.
1110 DumperOptions options = new DumperOptions();
1111 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1112 Yaml yaml = new Yaml(options);
1114 Map<String, Object> node = new HashMap<>();
1115 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1116 .getLeft(), nodeNameValue.getValue());
1117 mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1119 return yaml.dumpAsMap(mapToConvert);
1122 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1123 validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1124 return Either.left(true);
1127 public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1128 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1129 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1130 String nodeName, boolean isNested) {
1132 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
1133 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1134 Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
1135 return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1136 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1137 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested)
1138 .left().on(this::failOnCertification);
1141 private ImmutablePair<Resource,ActionStatus> failOnCertification(ResponseFormat error) {
1142 throw new ComponentException(error);
1145 private UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
1146 String nodeName, User user) {
1147 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1149 // validate nodetype name prefix
1150 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1151 log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1152 Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1153 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1154 yamlName, resourceMetaData.getName(), nodeName);
1157 String actualName = this.getNodeTypeActualName(nodeName);
1158 String namePrefix = nodeName.replace(actualName, "");
1159 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1161 // if we import from csar, the node_type name can be
1162 // org.openecomp.resource.abstract.node_name - in this case we always
1164 if (resourceType.equals(Constants.ABSTRACT)) {
1165 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1168 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1169 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1170 ResourceTypeEnum.values());
1171 throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
1172 yamlName, resourceMetaData.getName(), nodeName);
1176 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1178 // Setting type from name
1179 String type = resourceType.toUpperCase();
1180 resourceMetaData.setResourceType(type);
1182 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1183 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1184 resourceMetaData.setContactId(user.getUserId());
1185 resourceMetaData.setVendorName(resourceVf.getVendorName());
1186 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1189 List<String> tags = new ArrayList<>();
1190 tags.add(resourceMetaData.getName());
1191 resourceMetaData.setTags(tags);
1194 CategoryDefinition category = new CategoryDefinition();
1195 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1196 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1197 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1198 category.addSubCategory(subCategory);
1199 List<CategoryDefinition> categories = new ArrayList<>();
1200 categories.add(category);
1201 resourceMetaData.setCategories(categories);
1203 return resourceMetaData;
1206 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1207 Map<String, NodeTypeInfo> nodesInfo) {
1208 Resource cvfc = new Resource();
1209 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1210 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1211 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1212 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1213 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1214 cvfc.setAbstract(true);
1215 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1216 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1217 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1218 cvfc.setContactId(csarInfo.getModifier().getUserId());
1219 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1220 cvfc.setVendorName(resourceVf.getVendorName());
1221 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1222 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1223 cvfc.setToscaResourceName(
1224 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1226 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1228 List<String> tags = new ArrayList<>();
1229 tags.add(cvfc.getName());
1232 CategoryDefinition category = new CategoryDefinition();
1233 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1234 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1235 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1236 category.addSubCategory(subCategory);
1237 List<CategoryDefinition> categories = new ArrayList<>();
1238 categories.add(category);
1239 cvfc.setCategories(categories);
1241 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1242 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1243 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1248 private String buildCvfcName(String resourceVfName, String nodeName) {
1249 String nameWithouNamespacePrefix = nodeName
1250 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1251 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1252 String resourceType = findTypes[0];
1253 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1254 return addCvfcSuffixToResourceName(resourceName);
1257 private Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
1258 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1259 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1260 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1261 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1262 boolean shouldLock, boolean inTransaction, String nodeName) {
1264 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1267 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1269 if (lockResult.isRight()) {
1270 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1271 throw new ComponentException(lockResult.right().value());
1273 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1276 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1277 Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
1278 resource = createResourceTransaction(resource,
1279 csarInfo.getModifier(), isNormative);
1280 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1281 log.trace("************* Going to add inputs from yaml {}", yamlName);
1282 if (resource.shouldGenerateInputs())
1283 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
1285 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1286 resource = createInputsOnResource(resource, inputs);
1287 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1289 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1291 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1293 resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1294 topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1295 nodeTypesArtifactsToCreate, nodeName);
1296 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1297 // validate update vf module group names
1298 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1299 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1300 if (validateUpdateVfGroupNamesRes.isRight()) {
1301 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1302 throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
1304 // add groups to resource
1305 Map<String, GroupDefinition> groups;
1306 log.trace("************* Going to add groups from yaml {}", yamlName);
1308 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1309 groups = validateUpdateVfGroupNamesRes.left().value();
1311 groups = parsedToscaYamlInfo.getGroups();
1314 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1316 if (createGroupsOnResource.isRight()) {
1317 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1318 throw new ComponentException(createGroupsOnResource.right().value());
1320 resource = createGroupsOnResource.left().value();
1321 log.trace("************* Finished to add groups from yaml {}", yamlName);
1323 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1325 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1326 nodeTypesArtifactsToCreate);
1328 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1329 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1330 if (createArtifactsEither.isRight()) {
1331 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1332 throw new ComponentException(createArtifactsEither.right().value());
1335 resource = getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
1337 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1338 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1339 ASDCKpiApi.countCreatedResourcesKPI();
1342 } catch(ComponentException|StorageException e) {
1343 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
1346 if (!inTransaction) {
1350 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1351 NodeTypeEnum.Resource);
1356 private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1357 if(!inTransaction) {
1358 titanDao.rollback();
1360 if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
1361 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1362 log.debug("Found {} newly created artifacts to deleted, the component name: {}",createdArtifacts.size(), resource.getName());
1366 private Resource getResourceWithGroups(String resourceId) {
1368 ComponentParametersView filter = new ComponentParametersView();
1369 filter.setIgnoreGroups(false);
1370 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
1371 if (updatedResource.isRight()) {
1372 rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
1374 return updatedResource.left().value();
1377 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
1378 Map<String, GroupDefinition> groups) {
1379 if (groups != null && !groups.isEmpty()) {
1380 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
1382 handleGroupsProperties(resource, groups);
1383 fillGroupsFinalFields(groupsAsList);
1384 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1385 groupsAsList, true);
1386 if (createGroups.isRight()) {
1387 return Either.right(createGroups.right().value());
1390 return Either.left(resource);
1392 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1393 .getToscaElement(resource.getUniqueId());
1394 if (updatedResource.isRight()) {
1395 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1396 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1397 return Either.right(responseFormat);
1399 return Either.left(updatedResource.left().value());
1402 private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
1403 List<InputDefinition> inputs = resource.getInputs();
1404 if (MapUtils.isNotEmpty(groups)) {
1407 .filter(g -> isNotEmpty(g.getProperties()))
1408 .flatMap(g -> g.getProperties().stream())
1409 .forEach(p -> handleGetInputs(p, inputs));
1413 private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
1414 if (isNotEmpty(property.getGetInputValues())) {
1415 if (inputs == null || inputs.isEmpty()) {
1416 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
1417 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
1419 .map(GetInputValueDataDefinition::getInputName)
1420 .collect(toList()).toString());
1422 ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
1423 while (getInputValuesIter.hasNext()) {
1424 GetInputValueDataDefinition getInput = getInputValuesIter.next();
1425 InputDefinition input = findInputByName(inputs, getInput);
1426 getInput.setInputId(input.getUniqueId());
1427 if (getInput.getGetInputIndex() != null) {
1428 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
1429 input = findInputByName(inputs, getInputIndex);
1430 getInputIndex.setInputId(input.getUniqueId());
1431 getInputValuesIter.add(getInputIndex);
1437 private InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
1438 Optional<InputDefinition> inputOpt = inputs.stream()
1439 .filter(p -> p.getName().equals(getInput.getInputName()))
1441 if (!inputOpt.isPresent()) {
1442 log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
1443 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
1445 return inputOpt.get();
1448 private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
1449 groupsAsList.forEach(groupDefinition -> {
1450 groupDefinition.setInvariantName(groupDefinition.getName());
1451 groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
1455 private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
1456 if (isEmpty(groups)) {
1459 updateOrCreateGroups(resource, groups);
1461 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1462 .getToscaElement(resource.getUniqueId());
1463 if (updatedResource.isRight()) {
1464 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1465 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1467 return updatedResource.left().value();
1470 private void updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
1471 List<GroupDefinition> groupsFromResource = resource.getGroups();
1472 List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
1473 List<GroupDefinition> groupsToUpdate = new ArrayList<>();
1474 List<GroupDefinition> groupsToDelete = new ArrayList<>();
1475 List<GroupDefinition> groupsToCreate = new ArrayList<>();
1476 if (isNotEmpty(groupsFromResource)) {
1477 addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
1478 addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
1480 groupsToCreate.addAll(groupsAsList);
1482 if (isNotEmpty(groupsToCreate)) {
1483 fillGroupsFinalFields(groupsToCreate);
1484 if (isNotEmpty(groupsFromResource)) {
1485 groupBusinessLogic.addGroups(resource,
1486 groupsToCreate, true)
1488 .on(this::throwComponentException);
1490 groupBusinessLogic.createGroups(resource,
1491 groupsToCreate, true)
1493 .on(this::throwComponentException);
1496 if (isNotEmpty(groupsToDelete)) {
1497 groupBusinessLogic.deleteGroups(resource, groupsToDelete)
1499 .on(this::throwComponentException);
1501 if (isNotEmpty(groupsToUpdate)) {
1502 groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
1504 .on(this::throwComponentException);
1508 private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToDelete) {
1509 for (GroupDefinition group : groupsFromResource) {
1510 Optional<GroupDefinition> op = groupsAsList.stream()
1511 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1512 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1513 groupsToDelete.add(group);
1518 private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList, List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
1519 for (GroupDefinition group : groupsAsList) {
1520 Optional<GroupDefinition> op = groupsFromResource.stream()
1521 .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
1522 if (op.isPresent()) {
1523 GroupDefinition groupToUpdate = op.get();
1524 groupToUpdate.setMembers(group.getMembers());
1525 groupToUpdate.setCapabilities(group.getCapabilities());
1526 groupToUpdate.setProperties(group.getProperties());
1527 groupsToUpdate.add(groupToUpdate);
1529 groupsToCreate.add(group);
1534 private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
1535 List<InputDefinition> resourceProperties = resource.getInputs();
1536 if (MapUtils.isNotEmpty(inputs)|| isNotEmpty(resourceProperties)) {
1538 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1540 if (createInputs.isRight()) {
1541 throw new ComponentException(createInputs.right().value());
1546 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1547 .getToscaElement(resource.getUniqueId());
1548 if (updatedResource.isRight()) {
1549 throw new ComponentException(componentsUtils.getResponseFormatByResource(
1550 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
1552 return updatedResource.left().value();
1555 private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1557 List<GroupDefinition> result = new ArrayList<>();
1558 List<ComponentInstance> componentInstances = component.getComponentInstances();
1560 if (groups != null) {
1561 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1562 if (validateCyclicGroupsDependencies.isRight()) {
1563 throw new ComponentException(validateCyclicGroupsDependencies.right().value());
1565 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1566 String groupName = entry.getKey();
1567 GroupDefinition groupDefinition = entry.getValue();
1568 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1569 updatedGroupDefinition.setMembers(null);
1570 Map<String, String> members = groupDefinition.getMembers();
1571 if (members != null) {
1572 updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
1574 result.add(updatedGroupDefinition);
1580 private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component, List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
1581 Set<String> compInstancesNames = members.keySet();
1583 if (CollectionUtils.isEmpty(componentInstances)) {
1584 String membersAstString = compInstancesNames.stream().collect(joining(","));
1585 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
1586 membersAstString, groupName, component.getNormalizedName());
1587 throw new ComponentException(componentsUtils.getResponseFormat(
1588 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1589 component.getNormalizedName(), getComponentTypeForResponse(component)));
1591 // Find all component instances with the member names
1592 Map<String, String> memberNames = componentInstances.stream()
1593 .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1594 memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
1595 Map<String, String> relevantInstances = memberNames.entrySet().stream()
1596 .filter(n -> compInstancesNames.contains(n.getKey()))
1597 .collect(toMap(Entry::getKey, Entry::getValue));
1599 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1601 List<String> foundMembers = new ArrayList<>();
1602 if (relevantInstances != null) {
1603 foundMembers = relevantInstances.keySet().stream().collect(toList());
1605 compInstancesNames.removeAll(foundMembers);
1606 String membersAstString = compInstancesNames.stream().collect(joining(","));
1607 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
1608 groupName, component.getNormalizedName());
1609 throw new ComponentException(componentsUtils.getResponseFormat(
1610 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
1611 component.getNormalizedName(), getComponentTypeForResponse(component)));
1613 updatedGroupDefinition.setMembers(relevantInstances);
1617 * This Method validates that there is no cyclic group dependencies. meaning
1618 * group A as member in group B which is member in group A
1623 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1625 Either<Boolean, ResponseFormat> result = Either.left(true);
1627 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1628 while (allGroupsItr.hasNext() && result.isLeft()) {
1629 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1630 // Fetches a group member A
1631 String groupAName = groupAEntry.getKey();
1632 // Finds all group members in group A
1633 Set<String> allGroupAMembersNames = new HashSet<>();
1634 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1635 // If A is a group member of itself found cyclic dependency
1636 if (allGroupAMembersNames.contains(groupAName)) {
1637 ResponseFormat responseFormat = componentsUtils
1638 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1639 result = Either.right(responseFormat);
1642 } catch (Exception e) {
1643 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1644 result = Either.right(responseFormat);
1645 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1651 * This Method fills recursively the set groupMembers with all the members
1652 * of the given group which are also of type group.
1656 * @param allGroupMembers
1659 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
1660 Set<String> allGroupMembers) {
1662 // Found Cyclic dependency
1663 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1666 GroupDefinition groupDefinition = allGroups.get(groupName);
1667 // All Members Of Current Group Resource Instances & Other Groups
1668 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1669 // Filtered Members Of Current Group containing only members which
1671 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1672 // Keep Only Elements of type group and not Resource Instances
1673 filter(allGroups::containsKey).
1674 // Add Filtered Elements to main Set
1675 peek(allGroupMembers::add).
1679 // Recursively call the method for all the filtered group members
1680 for (String innerGroupName : currGroupFilteredMembers) {
1681 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1686 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
1687 Set<String> allGroupMembers) {
1689 boolean stop = false;
1690 // In Case Not Group Stop
1691 if (!allGroups.containsKey(groupName)) {
1694 // In Case Group Has no members stop
1696 GroupDefinition groupDefinition = allGroups.get(groupName);
1697 stop = isEmpty(groupDefinition.getMembers());
1700 // In Case all group members already contained stop
1702 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1703 Set<String> membersOfTypeGroup = allMembers.stream().
1704 // Filter In Only Group members
1705 filter(allGroups::containsKey).
1708 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1713 private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
1714 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
1715 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1716 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1717 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1720 log.debug("************* Going to create all nodes {}", yamlName);
1721 handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
1722 nodeTypesInfo, csarInfo, nodeName);
1723 log.debug("************* Finished to create all nodes {}", yamlName);
1724 log.debug("************* Going to create all resource instances {}", yamlName);
1725 resource = createResourceInstances(yamlName, resource,
1726 uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
1727 log.debug("************* Finished to create all resource instances {}", yamlName);
1728 log.debug("************* Going to create all relations {}", yamlName);
1729 resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1730 log.debug("************* Finished to create all relations {}", yamlName);
1731 log.debug("************* Going to create positions {}", yamlName);
1732 compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1733 log.debug("************* Finished to set positions {}", yamlName);
1737 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
1738 List<ArtifactDefinition> artifactsToAdd) {
1739 List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
1741 artifactsToAdd.stream().forEach(a -> {
1742 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1743 vfcArtifacts.add(a);
1745 log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1751 @SuppressWarnings("unchecked")
1752 private void handleNodeTypes(String yamlName, Resource resource,
1753 String topologyTemplateYaml, boolean needLock,
1754 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1755 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1756 CsarInfo csarInfo, String nodeName) {
1758 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1759 if (nodeTypeEntry.getValue().isNested()) {
1761 handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
1762 nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1763 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1766 Map<String, Object> mappedToscaTemplate = null;
1767 if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo)
1768 && nodeTypesInfo.containsKey(nodeName)) {
1769 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1771 if (isEmpty(mappedToscaTemplate)) {
1772 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1774 createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1775 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1776 } catch(ComponentException e){
1777 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
1778 : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
1779 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1781 } catch (StorageException e){
1782 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
1783 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1786 // add the created node types to the cache although they are not in the
1788 csarInfo.getCreatedNodes().values().stream()
1789 .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1792 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
1793 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1794 boolean inTransaction) {
1796 if (csarInfo.getCsar() != null) {
1797 String vendorLicenseModelId = null;
1798 String vfLicenseModelId = null;
1800 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1801 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1802 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1803 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1804 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
1805 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1807 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
1808 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1814 // Specific Behavior for license artifacts
1815 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1816 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
1817 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1818 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
1819 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
1821 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
1822 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
1823 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
1824 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
1825 artifactOperation, null, true, shouldLock, inTransaction);
1827 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
1828 createdArtifacts, shouldLock, inTransaction, artifactOperation);
1829 if (eitherCreateResult.isRight()) {
1830 return Either.right(eitherCreateResult.right().value());
1832 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
1833 .getToscaElement(resource.getUniqueId());
1834 if (eitherGerResource.isRight()) {
1835 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1836 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
1838 return Either.right(responseFormat);
1841 resource = eitherGerResource.left().value();
1843 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1845 if (artifacsMetaCsarStatus.isLeft()) {
1846 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1847 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1848 Either<Resource, ResponseFormat> createArtifactsFromCsar;
1849 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1850 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1852 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1855 if (createArtifactsFromCsar.isRight()) {
1856 log.debug("Couldn't create artifacts from artifacts.meta");
1857 return Either.right(createArtifactsFromCsar.right().value());
1860 return Either.left(createArtifactsFromCsar.left().value());
1863 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
1867 return Either.left(resource);
1871 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
1872 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
1873 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
1874 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
1875 boolean inTransaction) {
1876 byte[] artifactFileBytes = null;
1878 if (csarInfo.getCsar().containsKey(artifactPath)) {
1879 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
1881 Either<Boolean, ResponseFormat> result = Either.left(true);
1882 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
1883 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
1884 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
1885 shouldLock, inTransaction);
1886 if (handleDelete.isRight()) {
1887 result = Either.right(handleDelete.right().value());
1893 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
1894 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1895 ArtifactOperationEnum.CREATE);
1899 if (artifactFileBytes != null) {
1900 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
1901 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
1902 artifactFileBytes, null, isFromCsar);
1903 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
1904 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
1905 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1906 if (eitherNonMetaArtifacts.isRight()) {
1907 BeEcompErrorManager.getInstance()
1908 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
1909 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
1910 ErrorSeverity.WARNING);
1911 return Either.right(eitherNonMetaArtifacts.right().value());
1917 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
1918 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
1922 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
1923 List<ArtifactDefinition> createdArtifacts,
1924 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
1925 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
1926 && eitherNonMetaArtifacts.isLeft()) {
1927 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
1928 if (eitherResult.isLeft()) {
1929 createdArtifacts.add(eitherResult.left().value());
1935 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
1936 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
1937 ArtifactOperationInfo artifactOperation) {
1939 Either<Resource, ResponseFormat> resStatus = null;
1940 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
1943 Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
1944 if (artifactPathAndNameList.isRight()) {
1945 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
1946 ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
1948 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
1950 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
1951 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
1952 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
1954 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
1955 resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
1957 if (findVfCsarArtifactsToHandleRes.isRight()) {
1958 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
1960 if (resStatus == null) {
1961 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
1964 if (resStatus == null && vfCsarArtifactsToHandle != null) {
1965 resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
1967 if (resStatus == null) {
1968 resStatus = Either.left(resource);
1970 } catch (Exception e) {
1971 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1972 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
1974 CsarUtils.handleWarningMessages(collectedWarningMessages);
1979 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) {
1980 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
1983 Optional<ResponseFormat> optionalCreateInDBError =
1984 // Stream of artifacts to be created
1985 currArtifactOperationPair.getValue().stream()
1986 // create each artifact
1987 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
1988 e.getArtifactName(), e.getArtifactType().getType(),
1989 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
1990 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
1991 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
1992 currArtifactOperationPair.getKey()),
1993 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
1994 // filter in only error
1995 .filter(Either::isRight).
1996 // Convert the error from either to
1998 map(e -> e.right().value()).
1999 // Check if an error occurred
2001 // Error found on artifact Creation
2002 if (optionalCreateInDBError.isPresent()) {
2003 resStatus = Either.right(optionalCreateInDBError.get());
2010 private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo, Map<String, Set<List<String>>> collectedWarningMessages) {
2011 List<NonMetaArtifactInfo> artifactPathAndNameList =
2012 // Stream of file paths contained in csar
2013 csarInfo.getCsar().entrySet().stream()
2014 // Filter in only VF artifact path location
2015 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2017 // Validate and add warnings
2018 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2019 collectedWarningMessages))
2020 // Filter in Non Warnings
2021 .filter(Either::isLeft)
2022 // Convert from Either to NonMetaArtifactInfo
2023 .map(e -> e.left().value())
2026 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2027 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2028 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2029 return Either.right(nonMetaArtifactInfo.getArtifactName());
2032 return Either.left(artifactPathAndNameList);
2035 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2036 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2038 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2039 // collect all Deployment and Informational artifacts of VF
2040 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2041 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2043 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2044 existingArtifacts.addAll(resource.getArtifacts().values());
2046 existingArtifacts = existingArtifacts.stream()
2047 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2048 // was created from HEAT.meta
2049 .filter(this::isNonMetaArtifact).collect(toList());
2051 List<String> artifactsToIgnore = new ArrayList<>();
2052 // collect IDs of Artifacts of VF which belongs to any group
2053 if (resource.getGroups() != null) {
2054 resource.getGroups().stream().forEach(g -> {
2055 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
2056 artifactsToIgnore.addAll(g.getArtifacts());
2060 existingArtifacts = existingArtifacts.stream()
2061 // filter artifacts which belongs to any group
2062 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
2063 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2066 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2067 boolean result = true;
2068 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2074 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2075 boolean result = true;
2076 if (artifact.getArtifactType() == null
2077 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2078 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2084 private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
2085 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2086 log.debug("#createResourceInstancesRelations - Going to create relations ");
2087 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2088 if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) {
2089 log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
2090 BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations","No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
2091 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
2093 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2094 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
2095 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2096 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2097 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2098 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2099 Map<String, Resource> originCompMap = new HashMap<>();
2100 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2101 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2103 log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
2104 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2105 if (allDataTypes.isRight()) {
2106 TitanOperationStatus status = allDataTypes.right().value();
2107 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2108 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2109 throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2110 DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
2113 Resource finalResource = resource;
2114 uploadResInstancesMap
2116 .forEach(i ->processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
2117 instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
2118 instArtifacts, instAttributes, originCompMap, instInputs, i));
2120 associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
2121 associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
2122 associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
2123 associateArtifactsToInstances(yamlName, resource, instArtifacts);
2124 associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
2125 associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
2127 resource = getResourceAfterCreateRelations(resource);
2129 addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
2130 associateResourceInstances(yamlName, resource, relations);
2131 handleSubstitutionMappings(resource, uploadResInstancesMap);
2132 log.debug("************* in create relations, getResource start");
2133 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2134 log.debug("************* in create relations, getResource end");
2135 if (eitherGetResource.isRight()) {
2136 throw new ComponentException(componentsUtils.getResponseFormatByResource(
2137 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
2139 return eitherGetResource.left().value();
2142 private Resource getResourceAfterCreateRelations(Resource resource) {
2143 ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
2144 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2145 .getToscaElement(resource.getUniqueId(), parametersView);
2147 if (eitherGetResource.isRight()) {
2148 throwComponentExceptionByResource(eitherGetResource.right().value(),resource);
2150 return eitherGetResource.left().value();
2153 private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
2154 StorageOperationStatus addArtToInst;
2155 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2156 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2157 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2159 throw new ComponentException(componentsUtils
2160 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2164 private ComponentParametersView getComponentFilterAfterCreateRelations() {
2165 ComponentParametersView parametersView = new ComponentParametersView();
2166 parametersView.disableAll();
2167 parametersView.setIgnoreComponentInstances(false);
2168 parametersView.setIgnoreComponentInstancesProperties(false);
2169 parametersView.setIgnoreCapabilities(false);
2170 parametersView.setIgnoreRequirements(false);
2171 parametersView.setIgnoreGroups(false);
2172 return parametersView;
2175 private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map<String, List<PropertyDefinition>> instAttributes) {
2176 StorageOperationStatus addArtToInst;
2177 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2178 resource.getUniqueId());
2179 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2180 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2182 throw new ComponentException(componentsUtils
2183 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2187 private void associateOrAddCalculatedCapReq(String yamlName, Resource resource, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
2188 StorageOperationStatus addArtToInst;
2189 addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
2190 resource.getUniqueId());
2191 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2192 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2194 throw new ComponentException(componentsUtils
2195 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2199 private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
2200 StorageOperationStatus addArtToInst;
2202 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId());
2203 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2204 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2205 throw new ComponentException(componentsUtils
2206 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2210 private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
2211 StorageOperationStatus addArtToInst = toscaOperationFacade
2212 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2213 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2214 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2215 throw new ComponentException(componentsUtils
2216 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
2220 private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
2221 if (MapUtils.isNotEmpty(instInputs)) {
2222 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2223 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2224 if (addInputToInst.isRight()) {
2225 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2226 addInputToInst.right().value());
2227 throw new ComponentException(componentsUtils.getResponseFormat(
2228 componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
2233 private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
2234 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2235 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2236 if (addPropToInst.isRight()) {
2237 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2238 addPropToInst.right().value());
2239 throw new ComponentException(componentsUtils.getResponseFormat(
2240 componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
2244 private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2245 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2246 Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2247 if (getResourceRes.isRight()) {
2248 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2249 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2250 throw new ComponentException(responseFormat);
2252 getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
2253 uploadResInstancesMap);
2254 if (getResourceRes.isRight()) {
2255 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2256 componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
2257 throw new ComponentException(responseFormat);
2262 private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
2263 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2264 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2265 ComponentInstance currentCompInstance = null;
2266 for (ComponentInstance compInstance : componentInstancesList) {
2268 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2269 currentCompInstance = compInstance;
2274 if (currentCompInstance == null) {
2275 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2276 resource.getUniqueId());
2277 BeEcompErrorManager.getInstance().logInternalDataError(
2278 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2279 resource.getUniqueId(), ErrorSeverity.ERROR);
2280 ResponseFormat responseFormat = componentsUtils
2281 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2282 throw new ComponentException(responseFormat);
2285 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2286 if (addRelationToRiRes.getStatus() != 200) {
2287 throw new ComponentException(addRelationToRiRes);
2292 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) {
2293 Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
2294 .filter(i->i.getName().equals(uploadComponentInstanceInfo.getName()))
2296 if (!currentCompInstanceOpt.isPresent()) {
2297 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
2298 resource.getUniqueId());
2299 BeEcompErrorManager.getInstance().logInternalDataError(
2300 COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
2301 resource.getUniqueId(), ErrorSeverity.ERROR);
2302 ResponseFormat responseFormat = componentsUtils
2303 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2304 throw new ComponentException(responseFormat);
2306 ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
2307 String resourceInstanceId = currentCompInstance.getUniqueId();
2308 Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
2309 if (isNotEmpty(originResource.getRequirements())) {
2310 instRequirements.put(currentCompInstance, originResource.getRequirements());
2312 if (isNotEmpty(originResource.getCapabilities())) {
2313 processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
2314 currentCompInstance, originResource);
2316 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
2317 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2319 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
2320 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2322 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
2323 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2325 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2326 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2327 originResource, currentCompInstance, instProperties, allDataTypes.left().value());
2328 if (addPropertiesValueToRiRes.getStatus() != 200) {
2329 throw new ComponentException(addPropertiesValueToRiRes);
2332 addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2333 originResource, currentCompInstance, instInputs, allDataTypes.left().value());
2337 private Resource getOriginResource(String yamlName, Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
2338 Resource originResource;
2339 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2340 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2341 .getToscaFullElement(currentCompInstance.getComponentUid());
2342 if (getOriginResourceRes.isRight()) {
2343 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2344 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2345 getOriginResourceRes);
2346 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2347 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2348 throw new ComponentException(responseFormat);
2350 originResource = getOriginResourceRes.left().value();
2351 originCompMap.put(originResource.getUniqueId(), originResource);
2353 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2355 return originResource;
2358 private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) {
2359 Map<String, List<CapabilityDefinition>> originCapabilities;
2360 if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2361 originCapabilities = new HashMap<>();
2362 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2363 originResource.getCapabilities().forEach((k,v) -> addCapabilities(originCapabilities, k, v));
2364 uploadComponentInstanceInfo.getCapabilities().values().forEach(l-> addCapabilitiesProperties(newPropertiesMap, l));
2365 updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
2367 originCapabilities = originResource.getCapabilities();
2369 instCapabilties.put(currentCompInstance, originCapabilities);
2372 private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes, Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
2373 originCapabilities.values().stream()
2374 .flatMap(Collection::stream)
2375 .filter(c -> newPropertiesMap.containsKey(c.getName()))
2376 .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
2379 private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
2380 for (UploadCapInfo capability : capabilities) {
2381 if (isNotEmpty(capability.getProperties())) {
2382 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2383 .collect(toMap(UploadInfo::getName, p -> p)));
2388 private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
2389 List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
2391 originCapabilities.put(type, list);
2394 private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
2395 Map<String, DataTypeDefinition> allDataTypes) {
2396 properties.forEach(p->updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
2399 private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
2400 Map<String, DataTypeDefinition> allDataTypes) {
2401 String value = null;
2402 List<GetInputValueDataDefinition> getInputs = null;
2403 boolean isValidate = true;
2404 if (null != propertyInfo && propertyInfo.getValue() != null) {
2405 getInputs = propertyInfo.getGet_input();
2406 isValidate = getInputs == null || getInputs.isEmpty();
2408 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2410 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2411 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2414 property.setValue(value);
2415 return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2418 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2419 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2420 Either<Resource, StorageOperationStatus> updateRes = null;
2421 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2422 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2423 StorageOperationStatus status = toscaOperationFacade
2424 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2425 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2427 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2428 resource.getUniqueId(), status);
2429 updateRes = Either.right(status);
2431 if (updateRes == null) {
2432 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2433 updatedInstCapabilities, updatedInstRequirements);
2434 status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2435 resource.getUniqueId());
2436 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2438 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2439 resource.getUniqueId(), status);
2440 updateRes = Either.right(status);
2443 if (updateRes == null) {
2444 updateRes = Either.left(resource);
2449 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2450 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2451 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2452 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2454 componentInstances.stream().forEach(i -> {
2455 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2456 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2457 fillUpdatedInstRequirements(updatedInstRequirements, i,
2458 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2462 private void fillUpdatedInstRequirements(
2463 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2464 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2465 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2466 Set<String> updatedReqNames = new HashSet<>();
2467 if (isNotEmpty(requirementsNamesToUpdate)) {
2468 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2469 updatedRequirements.put(requirements.getKey(),
2470 requirements.getValue().stream()
2471 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2472 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2474 r.setParentName(r.getName());
2475 r.setName(requirementsNamesToUpdate.get(r.getName()));
2476 updatedReqNames.add(r.getName());
2478 }).collect(toList()));
2481 if (isNotEmpty(updatedRequirements)) {
2482 updatedInstRequirements.put(instance, updatedRequirements);
2486 private void fillUpdatedInstCapabilities(
2487 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2488 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2489 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2490 Set<String> updatedCapNames = new HashSet<>();
2491 if (isNotEmpty(capabilitiesNamesToUpdate)) {
2492 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2493 updatedCapabilities.put(requirements.getKey(),
2494 requirements.getValue().stream()
2495 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2496 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2498 c.setParentName(c.getName());
2499 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2500 updatedCapNames.add(c.getName());
2502 }).collect(toList()));
2505 if (isNotEmpty(updatedCapabilities)) {
2506 updatedInstCapabilties.put(instance, updatedCapabilities);
2510 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2511 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2512 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2514 ComponentInstance currentCompInstance = null;
2516 for (ComponentInstance compInstance : componentInstancesList) {
2518 if (compInstance.getName().equals(nodesInfoValue.getName())) {
2519 currentCompInstance = compInstance;
2525 if (currentCompInstance == null) {
2526 log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
2527 resource.getUniqueId());
2528 BeEcompErrorManager.getInstance().logInternalDataError(
2529 COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
2530 resource.getUniqueId(), ErrorSeverity.ERROR);
2531 return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2534 String resourceInstanceId = currentCompInstance.getUniqueId();
2536 Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
2538 if (regMap != null) {
2539 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2541 while (nodesRegValue.hasNext()) {
2542 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
2544 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
2545 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
2546 log.debug("Going to create relation {}", uploadRegInfo.getName());
2547 String regName = uploadRegInfo.getName();
2548 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
2549 regCapRelDef.setFromNode(resourceInstanceId);
2550 log.debug("try to find available requirement {} ", regName);
2551 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
2552 yamlName, nodesInfoValue, currentCompInstance,
2553 uploadRegInfo.getCapabilityName());
2554 if (eitherReqStatus.isRight()) {
2555 log.debug("failed to find available requirement {} status is {}", regName,
2556 eitherReqStatus.right().value());
2557 return eitherReqStatus.right().value();
2560 RequirementDefinition validReq = eitherReqStatus.left().value();
2561 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
2562 .getRelationships();
2563 if (reqAndRelationshipPairList == null) {
2564 reqAndRelationshipPairList = new ArrayList<>();
2566 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
2567 reqAndRelationshipPair.setRequirement(regName);
2568 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
2569 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
2570 RelationshipImpl relationship = new RelationshipImpl();
2571 relationship.setType(validReq.getCapability());
2572 reqAndRelationshipPair.setRelationships(relationship);
2574 ComponentInstance currentCapCompInstance = null;
2575 for (ComponentInstance compInstance : componentInstancesList) {
2576 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
2577 currentCapCompInstance = compInstance;
2582 if (currentCapCompInstance == null) {
2583 log.debug("The component instance with name {} not found on resource {} ",
2584 uploadRegInfo.getNode(), resource.getUniqueId());
2585 BeEcompErrorManager.getInstance().logInternalDataError(
2586 COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
2587 resource.getUniqueId(), ErrorSeverity.ERROR);
2588 return componentsUtils
2589 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2591 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
2592 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
2593 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
2594 currentCapCompInstance, uploadRegInfo);
2595 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
2596 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
2597 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
2598 if (aviableCapForRel == null) {
2599 log.debug("aviable capability was not found. req name is {} component instance is {}",
2600 validReq.getName(), currentCapCompInstance.getUniqueId());
2601 BeEcompErrorManager.getInstance().logInternalDataError(
2602 "aviable capability was not found. req name is " + validReq.getName()
2603 + " component instance is " + currentCapCompInstance.getUniqueId(),
2604 resource.getUniqueId(), ErrorSeverity.ERROR);
2605 return componentsUtils
2606 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2608 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
2609 capReqRel.setRelation(reqAndRelationshipPair);
2610 reqAndRelationshipPairList.add(capReqRel);
2611 regCapRelDef.setRelationships(reqAndRelationshipPairList);
2612 relations.add(regCapRelDef);
2615 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
2616 return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
2618 return componentsUtils.getResponseFormat(ActionStatus.OK);
2621 private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2622 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2623 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
2624 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2625 if (MapUtils.isNotEmpty(propMap)) {
2626 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
2627 List<ComponentInstanceInput> instPropList = new ArrayList<>();
2629 if (CollectionUtils.isEmpty( originResource.getInputs())) {
2630 log.debug("failed to find properties ");
2631 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
2633 originResource.getInputs().forEach(p->addInput(currPropertiesMap, p));
2634 for (List<UploadPropInfo> propertyList : propMap.values()) {
2635 processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
2637 currPropertiesMap.values().forEach(p->instPropList.add(new ComponentInstanceInput(p)));
2638 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
2642 private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
2643 UploadPropInfo propertyInfo = propertyList.get(0);
2644 String propName = propertyInfo.getName();
2645 if (!currPropertiesMap.containsKey(propName)) {
2646 log.debug("failed to find property {} ", propName);
2647 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2650 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
2651 ComponentInstanceInput property = null;
2653 String value = null;
2654 List<GetInputValueDataDefinition> getInputs = null;
2655 boolean isValidate = true;
2656 if (propertyInfo.getValue() != null) {
2657 getInputs = propertyInfo.getGet_input();
2658 isValidate = getInputs == null || getInputs.isEmpty();
2660 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2661 curPropertyDef.getType());
2663 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2664 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2667 String innerType = null;
2668 property = new ComponentInstanceInput(curPropertyDef, value, null);
2670 String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2672 property.setValue(validPropertyVAlue);
2674 if (isNotEmpty(getInputs)) {
2675 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2676 for (GetInputValueDataDefinition getInput : getInputs) {
2677 List<InputDefinition> inputs = resource.getInputs();
2678 if (CollectionUtils.isEmpty(inputs)) {
2679 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
2680 property, currentCompInstance.getUniqueId());
2681 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2684 Optional<InputDefinition> optional = inputs.stream()
2685 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
2686 if (!optional.isPresent()) {
2687 log.debug("Failed to find input {} ", getInput.getInputName());
2688 // @@TODO error message
2689 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2691 InputDefinition input = optional.get();
2692 getInput.setInputId(input.getUniqueId());
2693 getInputValues.add(getInput);
2695 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2696 processGetInput(getInputValues, inputs, getInputIndex);
2698 property.setGetInputValues(getInputValues);
2700 instPropList.add(property);
2701 // delete overriden property
2702 currPropertiesMap.remove(property.getName());
2705 private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs, GetInputValueDataDefinition getInputIndex) {
2706 Optional<InputDefinition> optional;
2707 if (getInputIndex != null) {
2708 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
2710 if (!optional.isPresent()) {
2711 log.debug("Failed to find input {} ", getInputIndex.getInputName());
2712 // @@TODO error message
2713 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2715 InputDefinition inputIndex = optional.get();
2716 getInputIndex.setInputId(inputIndex.getUniqueId());
2717 getInputValues.add(getInputIndex);
2721 private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
2722 String propName = prop.getName();
2723 if (!currPropertiesMap.containsKey(propName)) {
2724 currPropertiesMap.put(propName, prop);
2728 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
2729 Resource resource, Resource originResource, ComponentInstance currentCompInstance,
2730 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
2732 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
2733 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
2735 List<PropertyDefinition> listFromMap = originResource.getProperties();
2736 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
2737 log.debug("failed to find properties ");
2738 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
2740 if (listFromMap == null || listFromMap.isEmpty()) {
2741 return componentsUtils.getResponseFormat(ActionStatus.OK);
2743 for (PropertyDefinition prop : listFromMap) {
2744 String propName = prop.getName();
2745 if (!currPropertiesMap.containsKey(propName)) {
2746 currPropertiesMap.put(propName, prop);
2749 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
2750 if (propMap != null && propMap.size() > 0) {
2751 for (List<UploadPropInfo> propertyList : propMap.values()) {
2753 UploadPropInfo propertyInfo = propertyList.get(0);
2754 String propName = propertyInfo.getName();
2755 if (!currPropertiesMap.containsKey(propName)) {
2756 log.debug("failed to find property {} ", propName);
2757 return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
2760 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
2761 ComponentInstanceProperty property = null;
2763 String value = null;
2764 List<GetInputValueDataDefinition> getInputs = null;
2765 boolean isValidate = true;
2766 if (propertyInfo.getValue() != null) {
2767 getInputs = propertyInfo.getGet_input();
2768 isValidate = getInputs == null || getInputs.isEmpty();
2770 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2771 curPropertyDef.getType());
2773 value = getPropertyJsonStringValue(propertyInfo.getValue(),
2774 TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
2777 String innerType = null;
2778 property = new ComponentInstanceProperty(curPropertyDef, value, null);
2780 String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
2781 property.setValue(validatePropValue);
2783 if (getInputs != null && !getInputs.isEmpty()) {
2784 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
2785 for (GetInputValueDataDefinition getInput : getInputs) {
2786 List<InputDefinition> inputs = resource.getInputs();
2787 if (inputs == null || inputs.isEmpty()) {
2788 log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
2789 rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
2791 .map(GetInputValueDataDefinition::getInputName)
2792 .collect(toList()).toString());
2794 InputDefinition input = findInputByName(inputs, getInput);
2795 getInput.setInputId(input.getUniqueId());
2796 getInputValues.add(getInput);
2798 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
2799 if (getInputIndex != null) {
2800 input = findInputByName(inputs, getInputIndex);
2801 getInputIndex.setInputId(input.getUniqueId());
2802 getInputValues.add(getInputIndex);
2807 property.setGetInputValues(getInputValues);
2809 instPropList.add(property);
2810 // delete overriden property
2811 currPropertiesMap.remove(property.getName());
2814 // add rest of properties
2815 if (!currPropertiesMap.isEmpty()) {
2816 for (PropertyDefinition value : currPropertiesMap.values()) {
2817 instPropList.add(new ComponentInstanceProperty(value));
2820 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
2821 return componentsUtils.getResponseFormat(ActionStatus.OK);
2824 // US740820 Relate RIs according to capability name
2825 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
2826 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2827 if (null == uploadReqInfo.getCapabilityName()
2828 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
2832 return findAvailableCapability(validReq, currentCapCompInstance);
2834 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
2837 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
2838 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
2839 CapabilityDefinition cap = null;
2840 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
2841 if (!capMap.containsKey(validReq.getCapability())) {
2844 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
2845 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
2846 if (!capByName.isPresent()) {
2849 cap = capByName.get();
2851 if (isBoundedByOccurrences(cap)) {
2852 String leftOccurrences = cap.getLeftOccurrences();
2853 int left = Integer.parseInt(leftOccurrences);
2856 cap.setLeftOccurrences(String.valueOf(left));
2864 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
2865 Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
2866 if (capMap.containsKey(validReq.getCapability())) {
2867 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
2869 for (CapabilityDefinition cap : capList) {
2870 if (isBoundedByOccurrences(cap)) {
2871 String leftOccurrences = cap.getLeftOccurrences() != null ?
2872 cap.getLeftOccurrences() : cap.getMaxOccurrences();
2873 int left = Integer.parseInt(leftOccurrences);
2876 cap.setLeftOccurrences(String.valueOf(left));
2887 private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
2888 return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
2891 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
2892 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
2894 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
2895 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
2896 RequirementDefinition validRegDef = null;
2898 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
2899 for (RequirementDefinition reqDef : entry.getValue()) {
2900 if (reqDef.getName().equals(regName)) {
2901 if (reqDef.getMaxOccurrences() != null
2902 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2903 String leftOccurrences = reqDef.getLeftOccurrences();
2904 if (leftOccurrences == null) {
2905 leftOccurrences = reqDef.getMaxOccurrences();
2907 int left = Integer.parseInt(leftOccurrences);
2910 reqDef.setLeftOccurrences(String.valueOf(left));
2911 validRegDef = reqDef;
2917 validRegDef = reqDef;
2923 if (validRegDef != null) {
2928 for (RequirementDefinition reqDef : list) {
2929 if (reqDef.getName().equals(regName)) {
2930 if (reqDef.getMaxOccurrences() != null
2931 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
2932 String leftOccurrences = reqDef.getLeftOccurrences();
2933 if (leftOccurrences == null) {
2934 leftOccurrences = reqDef.getMaxOccurrences();
2936 int left = Integer.parseInt(leftOccurrences);
2939 reqDef.setLeftOccurrences(String.valueOf(left));
2940 validRegDef = reqDef;
2946 validRegDef = reqDef;
2952 if (validRegDef == null) {
2953 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
2954 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
2955 return Either.right(responseFormat);
2957 return Either.left(validRegDef);
2960 private Resource createResourceInstances(String yamlName, Resource resource,
2961 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2962 Map<String, Resource> nodeNamespaceMap) {
2964 Either<Resource, ResponseFormat> eitherResource = null;
2965 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
2966 if (isEmpty(uploadResInstancesMap)) {
2967 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
2968 throw new ComponentException(responseFormat);
2970 Map<String, Resource> existingNodeTypeMap = new HashMap<>();
2971 if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
2972 nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
2974 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
2975 uploadResInstancesMap
2977 .forEach(i->createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
2979 if (isNotEmpty(resourcesInstancesMap)) {
2980 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
2981 resourcesInstancesMap, false);
2982 if (status != null && status != StorageOperationStatus.OK) {
2983 log.debug("Failed to add component instances to container component {}", resource.getName());
2984 ResponseFormat responseFormat = componentsUtils
2985 .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
2986 eitherResource = Either.right(responseFormat);
2987 throw new ComponentException(eitherResource.right().value());
2990 log.debug("*************Going to get resource {}", resource.getUniqueId());
2991 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2992 .getToscaElement(resource.getUniqueId(), getComponentWithInstancesFilter());
2993 log.debug("*************finished to get resource {}", resource.getUniqueId());
2994 if (eitherGetResource.isRight()) {
2995 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2996 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2997 throw new ComponentException(responseFormat);
2999 if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) {
3000 log.debug("Error when create resource instance from csar. ComponentInstances list empty");
3001 BeEcompErrorManager.getInstance().logBeDaoSystemError(
3002 "Error when create resource instance from csar. ComponentInstances list empty");
3003 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3005 return eitherGetResource.left().value();
3008 private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
3009 Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
3010 Either<Resource, ResponseFormat> eitherResource;
3011 log.debug("*************Going to create resource instances {}", yamlName);
3012 // updating type if the type is node type name - we need to take the
3014 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3015 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3016 uploadComponentInstanceInfo
3017 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3019 Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3020 existingnodeTypeMap);
3022 ComponentInstance componentInstance = new ComponentInstance();
3023 componentInstance.setComponentUid(refResource.getUniqueId());
3024 ComponentTypeEnum containerComponentType = resource.getComponentType();
3025 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3026 if (containerNodeType.equals(NodeTypeEnum.Resource)
3027 && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3028 && isNotEmpty(refResource.getCapabilities())) {
3029 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3030 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
3031 refResource.getUniqueId(), refResource.getCapabilities(),
3032 uploadComponentInstanceInfo.getCapabilities());
3033 componentInstance.setCapabilities(validComponentInstanceCapabilities);
3035 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3037 "createResourceInstances - not found lates version for resource instance with name {} and type ",
3038 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3039 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3040 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3041 throw new ComponentException(responseFormat);
3043 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3044 componentInstance.setName(uploadComponentInstanceInfo.getName());
3045 componentInstance.setIcon(origResource.getIcon());
3046 resourcesInstancesMap.put(componentInstance, origResource);
3049 private ComponentParametersView getComponentWithInstancesFilter() {
3050 ComponentParametersView parametersView = new ComponentParametersView();
3051 parametersView.disableAll();
3052 parametersView.setIgnoreComponentInstances(false);
3053 parametersView.setIgnoreInputs(false);
3054 // inputs are read when creating
3055 // property values on instances
3056 parametersView.setIgnoreUsers(false);
3057 return parametersView;
3060 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3061 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3062 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3063 if (originCapabilities.containsKey(currEntry.getKey())) {
3064 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3067 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3068 capabilities.getValue().stream().forEach(cap -> {
3069 if (uploadedCapabilities.containsKey(cap.getName())) {
3070 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3071 c.setName(cap.getName());
3072 c.setType(cap.getType());
3080 private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
3081 Map<String, Resource> nodeNamespaceMap) {
3083 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3084 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3085 Resource refResource;
3086 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3087 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3089 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3090 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3091 if (findResourceEither.isRight()) {
3093 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3094 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3095 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3096 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3097 throw new ComponentException(responseFormat);
3099 refResource = findResourceEither.left().value();
3100 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3102 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3103 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3105 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3106 refResource.getName(), componentState);
3107 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3108 refResource.getComponentType().getValue(), refResource.getName(), componentState);
3109 throw new ComponentException(responseFormat);
3112 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3113 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3114 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3115 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3116 throw new ComponentException(responseFormat);
3122 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
3123 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
3124 boolean forceCertificationAllowed) {
3126 Either<Resource, ResponseFormat> result = null;
3128 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
3129 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
3130 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
3131 if (result.isRight()) {
3134 resource = result.left().value();
3136 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
3137 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
3138 resource, user, false, inTransaction, needLock);
3139 result = eitherPopulated.isLeft() ? Either.left(resource)
3140 : Either.right(eitherPopulated.right().value());
3143 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
3144 } catch (Exception e) {
3145 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
3146 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3148 if (result == null || result.isRight()) {
3149 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3150 if (!inTransaction) {
3151 titanDao.rollback();
3153 } else if (!inTransaction) {
3159 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
3160 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3161 return lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
3162 lifecycleChangeInfo, inTransaction, needLock);
3165 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
3166 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
3167 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
3171 public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(
3172 Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
3173 CsarInfo csarInfo, String nodeName, boolean isNested) {
3175 ImmutablePair<Resource, ActionStatus> result = null;
3176 // check if resource already exists (search by tosca name = type)
3177 boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
3178 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
3179 .getLatestByToscaResourceName(resource.getToscaResourceName());
3181 if (latestByToscaName.isLeft()) {
3182 Resource foundResource = latestByToscaName.left().value();
3183 // we don't allow updating names of top level types
3184 if (!isNestedResource &&
3185 !StringUtils.equals(resource.getName(), foundResource.getName())) {
3186 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
3187 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3188 log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
3189 foundResource.getName(), resource.getToscaResourceName());
3190 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
3191 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3192 throwComponentException(responseFormat);
3194 result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
3195 } else if (isNotFound(latestByToscaName)) {
3196 if (isNestedResource) {
3197 result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
3199 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3202 StorageOperationStatus status = latestByToscaName.right().value();
3203 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
3204 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3205 componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
3206 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
3207 throwComponentException(responseFormat);
3212 private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
3213 return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
3216 private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, boolean isNested, String nodeName) {
3217 Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(
3218 resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
3219 if (latestByToscaName.isLeft()) {
3220 Resource nestedResource = (Resource) latestByToscaName.left().value();
3221 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
3222 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
3223 ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
3224 if (eitherValidation.isRight()) {
3225 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3227 return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
3229 return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
3233 private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
3234 return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
3237 private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource,
3238 User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
3239 log.debug("resource with name {} does not exist. create new resource", resource.getName());
3240 validateResourceBeforeCreate(resource, user,
3241 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
3242 Resource createdResource = createResourceByDao(resource, user,
3243 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
3244 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource,
3245 ActionStatus.CREATED);
3246 ASDCKpiApi.countImportResourcesKPI();
3247 return resourcePair;
3250 public boolean isResourceExist(String resourceName) {
3251 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
3252 return latestByName.isLeft();
3255 private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
3256 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
3258 String lockedResourceId = oldResource.getUniqueId();
3259 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
3260 oldResource.getVersion(), oldResource.getLifecycleState());
3261 ImmutablePair<Resource, ActionStatus> resourcePair = null;
3263 lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
3264 oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
3265 mergeOldResourceMetadataWithNew(oldResource, newResource);
3267 validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
3268 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
3269 // contact info normalization
3270 newResource.setContactId(newResource.getContactId().toLowerCase());
3271 // non-updatable fields
3272 newResource.setCreatorUserId(user.getUserId());
3273 newResource.setCreatorFullName(user.getFullName());
3274 newResource.setLastUpdaterUserId(user.getUserId());
3275 newResource.setLastUpdaterFullName(user.getFullName());
3276 newResource.setUniqueId(oldResource.getUniqueId());
3277 newResource.setVersion(oldResource.getVersion());
3278 newResource.setInvariantUUID(oldResource.getInvariantUUID());
3279 newResource.setLifecycleState(oldResource.getLifecycleState());
3280 newResource.setUUID(oldResource.getUUID());
3281 newResource.setNormalizedName(oldResource.getNormalizedName());
3282 newResource.setSystemName(oldResource.getSystemName());
3283 if (oldResource.getCsarUUID() != null) {
3284 newResource.setCsarUUID(oldResource.getCsarUUID());
3286 if (oldResource.getImportedToscaChecksum() != null) {
3287 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
3289 newResource.setAbstract(oldResource.isAbstract());
3291 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
3292 newResource.setDerivedFrom(oldResource.getDerivedFrom());
3294 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
3295 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
3297 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
3298 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
3301 // created without tosca artifacts - add the placeholders
3302 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
3303 setToscaArtifactsPlaceHolders(newResource, user);
3305 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
3306 .overrideComponent(newResource, oldResource);
3308 if (overrideResource.isRight()) {
3309 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3310 componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
3311 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
3313 throwComponentException(responseFormat);
3316 log.debug("Resource updated successfully!!!");
3317 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3318 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3319 ResourceVersionInfo.newBuilder()
3320 .state(oldResource.getLifecycleState()
3322 .version(oldResource.getVersion())
3325 resourcePair = new ImmutablePair<>(overrideResource.left().value(),
3327 return resourcePair;
3329 if (resourcePair == null) {
3330 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
3331 titanDao.rollback();
3332 } else if (!inTransaction) {
3336 log.debug("unlock resource {}", lockedResourceId);
3337 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
3344 * Merge old resource with new. Keep old category and vendor name without
3347 * @param oldResource
3348 * @param newResource
3350 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
3352 // keep old category and vendor name without change
3353 // merge the rest of the resource metadata
3354 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
3355 newResource.setTags(oldResource.getTags());
3358 if (newResource.getDescription() == null) {
3359 newResource.setDescription(oldResource.getDescription());
3362 if (newResource.getVendorRelease() == null) {
3363 newResource.setVendorRelease(oldResource.getVendorRelease());
3366 if (newResource.getResourceVendorModelNumber() == null) {
3367 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
3370 if (newResource.getContactId() == null) {
3371 newResource.setContactId(oldResource.getContactId());
3374 newResource.setCategories(oldResource.getCategories());
3375 if (newResource.getVendorName() == null) {
3376 newResource.setVendorName(oldResource.getVendorName());
3380 private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
3381 boolean inTransaction, boolean needLock) {
3383 if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
3385 return lifecycleBusinessLogic.changeState(
3386 oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
3387 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
3389 .on(response -> failOnChangeState(response, user, oldResource, newResource));
3394 private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
3395 log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
3396 response.getFormattedMessage());
3397 componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
3398 ResourceVersionInfo.newBuilder()
3399 .state(oldResource.getLifecycleState().name())
3400 .version(oldResource.getVersion())
3402 throw new ComponentException(response);
3405 public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
3407 validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
3408 validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
3409 validateLifecycleTypesCreate(user, resource, actionEnum);
3410 validateResourceType(user, resource, actionEnum);
3411 resource.setCreatorUserId(user.getUserId());
3412 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
3413 resource.setContactId(resource.getContactId().toLowerCase());
3414 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
3415 String resourceSystemName;
3416 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
3417 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
3419 resourceSystemName = resource.getSystemName();
3421 resource.setToscaResourceName(CommonBeUtils
3422 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
3425 // Generate invariant UUID - must be here and not in operation since it
3426 // should stay constant during clone
3428 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
3429 resource.setInvariantUUID(invariantUUID);
3434 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
3435 AuditingActionEnum actionEnum) {
3436 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3437 if (resource.getResourceType() == null) {
3438 log.debug("Invalid resource type for resource");
3439 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3440 eitherResult = Either.right(errorResponse);
3441 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3443 return eitherResult;
3446 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
3447 AuditingActionEnum actionEnum) {
3448 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3449 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
3450 log.debug("validate interface lifecycle Types Exist");
3451 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
3452 while (intItr.hasNext() && eitherResult.isLeft()) {
3453 InterfaceDefinition interfaceDefinition = intItr.next();
3454 String intType = interfaceDefinition.getUniqueId();
3455 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
3456 .getInterface(intType);
3457 if (eitherCapTypeFound.isRight()) {
3458 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3459 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3460 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
3461 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
3462 intType, resource.getName());
3463 BeEcompErrorManager.getInstance()
3464 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
3465 log.debug("request to data model failed with error: {}",
3466 eitherCapTypeFound.right().value().name());
3469 ResponseFormat errorResponse = componentsUtils
3470 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
3471 eitherResult = Either.right(errorResponse);
3472 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3477 return eitherResult;
3480 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
3481 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3482 boolean inTransaction) {
3484 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
3485 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
3486 log.debug("validate capability Types Exist - capabilities section");
3488 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
3490 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
3491 eitherResult, typeEntry, inTransaction);
3492 if (eitherResult.isRight()) {
3493 return Either.right(eitherResult.right().value());
3498 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
3499 log.debug("validate capability Types Exist - requirements section");
3500 for (String type : resource.getRequirements().keySet()) {
3501 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
3502 resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
3503 if (eitherResult.isRight()) {
3504 return Either.right(eitherResult.right().value());
3509 return eitherResult;
3512 // @param typeObject- the object to which the validation is done
3513 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3514 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
3515 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
3516 boolean inTransaction) {
3517 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3518 .getCapabilityType(type, inTransaction);
3519 if (eitherCapTypeFound.isRight()) {
3520 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3521 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3522 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
3523 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
3524 resource.getName());
3525 BeEcompErrorManager.getInstance()
3526 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3528 log.debug("Trying to get capability type {} failed with error: {}", type,
3529 eitherCapTypeFound.right().value().name());
3530 ResponseFormat errorResponse = null;
3532 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
3534 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
3537 eitherResult = Either.right(errorResponse);
3538 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3540 return eitherResult;
3543 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
3544 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
3545 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
3546 boolean inTransaction) {
3547 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
3548 .getCapabilityType(typeEntry.getKey(), inTransaction);
3549 if (eitherCapTypeFound.isRight()) {
3550 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
3551 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
3552 CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
3553 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
3554 typeEntry.getKey(), resource.getName());
3555 BeEcompErrorManager.getInstance()
3556 .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
3558 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
3559 eitherCapTypeFound.right().value().name());
3560 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
3561 typeEntry.getKey());
3562 eitherResult = Either.right(errorResponse);
3563 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
3565 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
3566 if (capabilityTypeDefinition.getProperties() != null) {
3567 for (CapabilityDefinition capDef : typeEntry.getValue()) {
3568 List<ComponentInstanceProperty> properties = capDef.getProperties();
3569 if (properties == null || properties.isEmpty()) {
3570 properties = new ArrayList<>();
3571 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3572 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
3573 properties.add(newProp);
3576 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
3577 PropertyDefinition porpFromDef = prop.getValue();
3578 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
3579 for (ComponentInstanceProperty cip : properties) {
3580 if (!cip.getName().equals(porpFromDef.getName())) {
3581 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
3582 propsToAdd.add(newProp);
3585 if (!propsToAdd.isEmpty()) {
3586 properties.addAll(propsToAdd);
3590 capDef.setProperties(properties);
3593 return eitherResult;
3596 public Resource createResourceByDao(Resource resource, User user,
3597 AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
3600 // lock new resource name in order to avoid creation resource with same
3602 Resource createdResource = null;
3603 if (!inTransaction) {
3604 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
3606 if (lockResult.isRight()) {
3607 ResponseFormat responseFormat = lockResult.right().value();
3608 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3609 throw new ComponentException(responseFormat);
3612 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
3615 if (resource.deriveFromGeneric()) {
3616 handleResourceGenericType(resource);
3618 createdResource = createResourceTransaction(resource, user, isNormative
3620 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
3621 createdResource, actionEnum);
3622 ASDCKpiApi.countCreatedResourcesKPI();
3623 } catch(ComponentException e) {
3624 ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
3625 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3627 } catch (StorageException e){
3628 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
3629 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
3633 if (!inTransaction) {
3634 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
3635 NodeTypeEnum.Resource);
3638 return createdResource;
3641 private Resource createResourceTransaction(Resource resource, User user,
3642 boolean isNormative) {
3643 // validate resource name uniqueness
3644 log.debug("validate resource name");
3645 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
3646 resource.getName(), resource.getResourceType(), resource.getComponentType());
3647 if (eitherValidation.isRight()) {
3648 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
3649 eitherValidation.right().value());
3650 ResponseFormat errorResponse = componentsUtils
3651 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
3652 throw new ComponentException(errorResponse);
3654 if (eitherValidation.left().value()) {
3655 log.debug("resource with name: {}, already exists", resource.getName());
3656 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
3657 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
3658 throw new ComponentException(errorResponse);
3661 log.debug("send resource {} to dao for create", resource.getName());
3663 createArtifactsPlaceHolderData(resource, user);
3666 log.debug("enrich resource with creator, version and state");
3667 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
3668 resource.setVersion(INITIAL_VERSION);
3669 resource.setHighestVersion(true);
3670 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
3671 resource.setAbstract(false);
3674 return toscaOperationFacade.createToscaComponent(resource)
3676 .on(r->throwComponentExceptionByResource(r, resource));
3679 private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
3680 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3681 componentsUtils.convertFromStorageResponse(status), resource);
3682 throw new ComponentException(responseFormat);
3685 private void createArtifactsPlaceHolderData(Resource resource, User user) {
3686 // create mandatory artifacts
3688 // TODO it must be removed after that artifact uniqueId creation will be
3689 // moved to ArtifactOperation
3691 setInformationalArtifactsPlaceHolder(resource, user);
3692 setDeploymentArtifactsPlaceHolder(resource, user);
3693 setToscaArtifactsPlaceHolders(resource, user);
3696 @SuppressWarnings("unchecked")
3698 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
3699 Resource resource = (Resource) component;
3700 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
3701 if (artifactMap == null) {
3702 artifactMap = new HashMap<>();
3704 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
3705 .getConfiguration().getDeploymentResourceArtifacts();
3706 if (deploymentResourceArtifacts != null) {
3707 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
3708 deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
3710 resource.setDeploymentArtifacts(artifactMap);
3713 private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
3714 boolean shouldCreateArtifact = true;
3715 Map<String, Object> artifactDetails = (Map<String, Object>) v;
3716 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
3717 if (object != null) {
3718 List<String> artifactTypes = (List<String>) object;
3719 if (!artifactTypes.contains(resource.getResourceType().name())) {
3720 shouldCreateArtifact = false;
3724 log.info("resource types for artifact placeholder {} were not defined. default is all resources",
3727 if (shouldCreateArtifact) {
3728 if (artifactsBusinessLogic != null) {
3729 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3730 resource.getUniqueId(), k, (Map<String, Object>) v,
3731 user, ArtifactGroupTypeEnum.DEPLOYMENT);
3732 if (artifactDefinition != null
3733 && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
3734 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3740 @SuppressWarnings("unchecked")
3741 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
3742 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
3743 if (artifactMap == null) {
3744 artifactMap = new HashMap<>();
3746 String resourceUniqueId = resource.getUniqueId();
3747 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
3748 .getExcludeResourceCategory();
3749 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
3750 .getExcludeResourceType();
3751 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
3752 .getConfiguration().getInformationalResourceArtifacts();
3753 List<CategoryDefinition> categories = resource.getCategories();
3754 boolean isCreateArtifact = true;
3755 if (exludeResourceCategory != null) {
3756 String category = categories.get(0).getName();
3757 isCreateArtifact = exludeResourceCategory.stream().noneMatch(e->e.equalsIgnoreCase(category));
3759 if (isCreateArtifact && exludeResourceType != null) {
3760 String resourceType = resource.getResourceType().name();
3761 isCreateArtifact = exludeResourceType.stream().noneMatch(e->e.equalsIgnoreCase(resourceType));
3763 if (informationalResourceArtifacts != null && isCreateArtifact) {
3764 Set<String> keys = informationalResourceArtifacts.keySet();
3765 for (String informationalResourceArtifactName : keys) {
3766 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
3767 .get(informationalResourceArtifactName);
3768 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
3769 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
3770 ArtifactGroupTypeEnum.INFORMATIONAL);
3771 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
3775 resource.setArtifacts(artifactMap);
3785 public ResponseFormat deleteResource(String resourceId, User user) {
3786 ResponseFormat responseFormat;
3787 validateUserExists(user, DELETE_RESOURCE, false);
3789 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
3790 if (resourceStatus.isRight()) {
3791 log.debug("failed to get resource {}", resourceId);
3792 return componentsUtils
3793 .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
3796 Resource resource = resourceStatus.left().value();
3798 StorageOperationStatus result = StorageOperationStatus.OK;
3799 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
3800 if (lockResult.isRight()) {
3801 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3806 result = markComponentToDelete(resource);
3807 if (result.equals(StorageOperationStatus.OK)) {
3808 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3810 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3811 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3813 return responseFormat;
3816 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3817 titanDao.rollback();
3821 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
3826 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
3827 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
3828 validateUserExists(user, DELETE_RESOURCE, false);
3829 Resource resource = null;
3830 StorageOperationStatus result = StorageOperationStatus.OK;
3833 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
3834 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
3835 if (resourceStatus.isRight()) {
3836 log.debug("failed to get resource {} version {}", resourceName, version);
3837 return componentsUtils.getResponseFormatByResource(
3838 componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
3841 resource = resourceStatus.left().value();
3844 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3845 titanDao.rollback();
3846 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3847 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
3852 if (resource != null) {
3853 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
3855 if (lockResult.isRight()) {
3856 result = StorageOperationStatus.GENERAL_ERROR;
3857 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3860 result = markComponentToDelete(resource);
3861 if (!result.equals(StorageOperationStatus.OK)) {
3862 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
3863 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
3864 return responseFormat;
3868 if (result == null || !result.equals(StorageOperationStatus.OK)) {
3869 titanDao.rollback();
3873 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
3876 return responseFormat;
3879 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
3882 validateUserExists(user, CREATE_RESOURCE, false);
3885 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
3886 if (storageStatus.isRight()) {
3887 log.debug("failed to get resource by id {}", resourceId);
3888 return Either.right(componentsUtils.getResponseFormatByResource(
3889 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
3891 if (!(storageStatus.left().value() instanceof Resource)) {
3892 return Either.right(componentsUtils.getResponseFormatByResource(
3893 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
3895 return Either.left(storageStatus.left().value());
3899 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
3902 validateUserExists(userId, "get Resource By Name And Version", false);
3904 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
3905 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
3906 if (getResource.isRight()) {
3907 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
3908 return Either.right(componentsUtils.getResponseFormatByResource(
3909 componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
3911 return Either.left(getResource.left().value());
3915 * updateResourceMetadata
3917 * @param user - modifier data (userId)
3918 * @param inTransaction TODO
3919 * @param resourceIdToUpdate - the resource identifier
3920 * @param newResource
3921 * @return Either<Resource , responseFormat>
3923 public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
3924 Resource currentResource, User user, boolean inTransaction) {
3926 validateUserExists(user.getUserId(), "update Resource Metadata", false);
3928 log.debug("Get resource with id {}", resourceIdToUpdate);
3929 boolean needToUnlock = false;
3930 boolean rollbackNeeded = true;
3933 if (currentResource == null) {
3934 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
3935 .getToscaElement(resourceIdToUpdate);
3936 if (storageStatus.isRight()) {
3937 throw new ComponentException(componentsUtils.getResponseFormatByResource(
3938 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
3941 currentResource = storageStatus.left().value();
3943 // verify that resource is checked-out and the user is the last
3945 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
3946 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3950 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
3951 NodeTypeEnum.Resource);
3952 if (!lockResult.equals(StorageOperationStatus.OK)) {
3953 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
3954 NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
3955 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
3956 ResponseFormat responseFormat = componentsUtils
3957 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
3958 throw new ComponentException(responseFormat);
3961 needToUnlock = true;
3963 // critical section starts here
3964 // convert json to object
3966 // Update and updated resource must have a non-empty "derivedFrom"
3968 // This code is not called from import resources, because of root
3969 // VF "derivedFrom" should be null (or ignored)
3970 if (ModelConverter.isAtomicComponent(currentResource)) {
3971 validateDerivedFromNotEmpty(null, newResource, null);
3972 validateDerivedFromNotEmpty(null, currentResource, null);
3974 newResource.setDerivedFrom(null);
3977 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
3978 user, currentResource, false, true);
3979 if (dataModelResponse.isRight()) {
3980 log.debug("failed to update resource metadata!!!");
3981 rollbackNeeded = true;
3982 throw new ComponentException(dataModelResponse.right().value());
3985 log.debug("Resource metadata updated successfully!!!");
3986 rollbackNeeded = false;
3987 return dataModelResponse.left().value();
3989 } catch (ComponentException|StorageException e){
3990 rollback(inTransaction, newResource, null, null);
3994 if (!inTransaction) {
3998 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
4003 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
4004 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
4005 updateVfModuleGroupsNames(currentResource, newResource);
4006 validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
4007 // Setting last updater and uniqueId
4008 newResource.setContactId(newResource.getContactId().toLowerCase());
4009 newResource.setLastUpdaterUserId(user.getUserId());
4010 newResource.setUniqueId(resourceIdToUpdate);
4011 // Cannot set highest version through UI
4012 newResource.setHighestVersion(currentResource.isHighestVersion());
4013 newResource.setCreationDate(currentResource.getCreationDate());
4015 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
4016 newResource, user.getUserId(), inTransaction);
4018 if (processUpdateOfDerivedFrom.isRight()) {
4019 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
4020 return Either.right(processUpdateOfDerivedFrom.right().value());
4023 log.debug("send resource {} to dao for update", newResource.getUniqueId());
4024 if (isNotEmpty(newResource.getGroups())) {
4025 for (GroupDefinition group : newResource.getGroups()) {
4026 if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
4027 groupBusinessLogic.validateAndUpdateGroupMetadata(
4028 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
4029 user, newResource.getComponentType(), group, true, false);
4033 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4034 .updateToscaElement(newResource);
4036 if (dataModelResponse.isRight()) {
4037 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4038 componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
4039 return Either.right(responseFormat);
4040 } else if (dataModelResponse.left().value() == null) {
4041 log.debug("No response from updateResource");
4042 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4044 return Either.left(dataModelResponse.left().value());
4048 private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
4049 if(currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())){
4050 List<GroupDefinition> updatedGroups = currentResource.getGroups()
4052 .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
4054 newResource.setGroups(updatedGroups);
4058 private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
4059 GroupDefinition updatedGroup = new GroupDefinition(currGroup);
4060 if(updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)){
4061 String prefix = updatedGroup.getName().substring(0, replacePattern.length());
4062 String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
4063 updatedGroup.setName(newGroupName);
4065 return updatedGroup;
4068 * validateResourceFieldsBeforeCreate
4070 * @param user - modifier data (userId)
4071 * @return Either<Boolean , ErrorResponse>
4073 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
4074 AuditingActionEnum actionEnum, boolean inTransaction) {
4075 validateComponentFieldsBeforeCreate(user, resource, actionEnum);
4076 // validate category
4077 log.debug("validate category");
4078 validateCategory(user, resource, actionEnum, inTransaction);
4079 // validate vendor name & release & model number
4080 log.debug("validate vendor name");
4081 validateVendorName(user, resource, actionEnum);
4082 log.debug("validate vendor release");
4083 validateVendorReleaseName(user, resource, actionEnum);
4084 log.debug("validate resource vendor model number");
4085 validateResourceVendorModelNumber(user, resource, actionEnum);
4087 log.debug("validate cost");
4088 validateCost(resource);
4089 // validate licenseType
4090 log.debug("validate licenseType");
4091 validateLicenseType(user, resource, actionEnum);
4092 // validate template (derived from)
4093 log.debug("validate derived from");
4094 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
4095 resource.setDerivedFrom(null);
4097 validateDerivedFromExist(user, resource, actionEnum);
4098 // warn about non-updatable fields
4099 checkComponentFieldsForOverrideAttempt(resource);
4100 String currentCreatorFullName = resource.getCreatorFullName();
4101 if (currentCreatorFullName != null) {
4102 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4105 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
4106 if (currentLastUpdaterFullName != null) {
4107 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4110 Long currentLastUpdateDate = resource.getLastUpdateDate();
4111 if (currentLastUpdateDate != null) {
4112 log.debug("Resource last update date is automatically set and cannot be updated");
4115 Boolean currentAbstract = resource.isAbstract();
4116 if (currentAbstract != null) {
4117 log.debug("Resource abstract is automatically set and cannot be updated");
4120 return Either.left(true);
4124 * validateResourceFieldsBeforeUpdate
4126 * @param currentResource - Resource object to validate
4129 private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
4130 boolean inTransaction, boolean isNested) {
4131 validateFields(currentResource, updateInfoResource, inTransaction, isNested);
4132 warnNonEditableFields(currentResource, updateInfoResource);
4135 private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
4136 String currentResourceVersion = currentResource.getVersion();
4137 String updatedResourceVersion = updateInfoResource.getVersion();
4139 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
4140 log.debug("Resource version is automatically set and cannot be updated");
4143 String currentCreatorUserId = currentResource.getCreatorUserId();
4144 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
4146 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
4147 log.debug("Resource Creator UserId is automatically set and cannot be updated");
4150 String currentCreatorFullName = currentResource.getCreatorFullName();
4151 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
4153 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
4154 log.debug("Resource Creator fullname is automatically set and cannot be updated");
4157 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
4158 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
4160 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
4161 log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
4164 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
4165 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
4167 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
4168 log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
4171 Long currentCreationDate = currentResource.getCreationDate();
4172 Long updatedCreationDate = updateInfoResource.getCreationDate();
4174 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
4175 log.debug("Resource Creation date is automatically set and cannot be updated");
4178 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
4179 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
4181 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
4182 log.debug("Resource last update date is automatically set and cannot be updated");
4185 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
4186 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
4188 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
4189 log.debug("Resource lifecycle state date is automatically set and cannot be updated");
4192 Boolean currentAbstract = currentResource.isAbstract();
4193 Boolean updatedAbstract = updateInfoResource.isAbstract();
4195 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
4196 log.debug("Resource abstract is automatically set and cannot be updated");
4199 Boolean currentHighestVersion = currentResource.isHighestVersion();
4200 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
4202 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
4203 log.debug("Resource highest version is automatically set and cannot be updated");
4206 String currentUuid = currentResource.getUUID();
4207 String updatedUuid = updateInfoResource.getUUID();
4209 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
4210 log.debug("Resource UUID is automatically set and cannot be updated");
4213 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
4214 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
4216 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
4217 log.debug("Resource Type cannot be updated");
4220 updateInfoResource.setResourceType(currentResource.getResourceType());
4222 String currentInvariantUuid = currentResource.getInvariantUUID();
4223 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
4225 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
4226 log.debug("Resource invariant UUID is automatically set and cannot be updated");
4227 updateInfoResource.setInvariantUUID(currentInvariantUuid);
4231 private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
4232 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
4233 log.debug("validate resource name before update");
4234 validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
4235 log.debug("validate description before update");
4236 validateDescriptionAndCleanup(null, updateInfoResource, null);
4237 log.debug("validate icon before update");
4238 validateIcon(currentResource, updateInfoResource, hasBeenCertified);
4239 log.debug("validate tags before update");
4240 validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
4241 log.debug("validate vendor name before update");
4242 validateVendorName(null, updateInfoResource, null);
4243 log.debug("validate resource vendor model number before update");
4244 validateResourceVendorModelNumber(currentResource, updateInfoResource);
4245 log.debug("validate vendor release before update");
4246 validateVendorReleaseName(null, updateInfoResource, null);
4247 log.debug("validate contact info before update");
4248 validateContactId(null, updateInfoResource, null);
4249 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
4250 validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
4251 log.debug("validate category before update");
4252 validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
4256 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
4257 String resourceNameUpdated = updateInfoResource.getName();
4258 String resourceNameCurrent = currentResource.getName();
4259 if (resourceNameCurrent.equals(resourceNameUpdated)) {
4262 // In case of CVFC type we should support the case of old VF with CVFC
4263 // instances that were created without the "Cvfc" suffix
4264 return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
4265 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
4268 private String addCvfcSuffixToResourceName(String resourceName) {
4269 return resourceName + "Cvfc";
4272 private void validateResourceName(Resource currentResource, Resource updateInfoResource,
4273 boolean hasBeenCertified, boolean isNested) {
4274 String resourceNameUpdated = updateInfoResource.getName();
4275 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
4276 if (isNested || !hasBeenCertified) {
4277 validateComponentName(null, updateInfoResource, null);
4278 validateResourceNameUniqueness(updateInfoResource);
4279 currentResource.setName(resourceNameUpdated);
4280 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
4281 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
4284 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
4285 resourceNameUpdated);
4286 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
4291 private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
4292 String iconUpdated = updateInfoResource.getIcon();
4293 String iconCurrent = currentResource.getIcon();
4294 if (!iconCurrent.equals(iconUpdated)) {
4295 if (!hasBeenCertified) {
4296 validateIcon(null, updateInfoResource, null);
4298 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
4299 throw new ComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
4304 private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
4305 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
4306 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
4307 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
4308 validateResourceVendorModelNumber(null, updateInfoResource, null);
4312 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
4313 boolean hasBeenCertified, boolean inTransaction) {
4314 validateCategory(null, updateInfoResource, null, inTransaction);
4315 if (hasBeenCertified) {
4316 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
4317 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
4318 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
4319 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
4320 if (!currentCategory.getName().equals(updateCategory.getName())
4321 || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
4322 log.info("Category {} cannot be updated once the resource has been certified once.",
4323 currentResource.getCategories());
4324 ResponseFormat errorResponse = componentsUtils
4325 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
4326 return Either.right(errorResponse);
4329 return Either.left(true);
4332 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
4333 Resource updateInfoResource, boolean hasBeenCertified) {
4335 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4336 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4337 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4338 || updatedDerivedFrom.isEmpty()) {
4339 log.trace("Update normative types");
4340 return Either.left(true);
4343 String derivedFromCurrent = currentDerivedFrom.get(0);
4344 String derivedFromUpdated = updatedDerivedFrom.get(0);
4346 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4347 if (!hasBeenCertified) {
4348 validateDerivedFromExist(null, updateInfoResource, null);
4350 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4351 currentResource, updateInfoResource, null);
4353 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4354 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4355 return validateDerivedFromExtending;
4359 // For derived from, we must know whether it was actually changed,
4360 // otherwise we must do no action.
4361 // Due to changes it inflicts on data model (remove artifacts,
4362 // properties...), it's not like a flat field which can be
4363 // overwritten if not changed.
4364 // So we must indicate that derived from is not changed
4365 updateInfoResource.setDerivedFrom(null);
4367 return Either.left(true);
4370 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
4371 Resource updateInfoResource, boolean hasBeenCertified) {
4373 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
4374 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
4375 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
4376 || updatedDerivedFrom.isEmpty()) {
4377 log.trace("Update normative types");
4378 return Either.left(true);
4381 String derivedFromCurrent = currentDerivedFrom.get(0);
4382 String derivedFromUpdated = updatedDerivedFrom.get(0);
4384 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
4385 if (!hasBeenCertified) {
4386 validateDerivedFromExist(null, updateInfoResource, null);
4388 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
4389 currentResource, updateInfoResource, null);
4391 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
4392 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
4393 return validateDerivedFromExtending;
4397 return Either.left(true);
4400 private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
4401 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
4404 String templateName = resource.getDerivedFrom().get(0);
4405 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4406 .validateToscaResourceNameExists(templateName);
4407 if (dataModelResponse.isRight()) {
4408 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4409 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
4410 log.debug("request to data model failed with error: {}", storageStatus);
4411 ResponseFormat responseFormat = componentsUtils
4412 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
4413 log.trace("audit before sending response");
4414 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4415 throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
4416 } else if (!dataModelResponse.left().value()) {
4417 log.info("resource template with name: {}, does not exists", templateName);
4418 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4419 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4420 throw new ComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
4424 // Tal G for extending inheritance US815447
4425 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
4426 Resource updateInfoResource, AuditingActionEnum actionEnum) {
4427 String currentTemplateName = currentResource.getDerivedFrom().get(0);
4428 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
4430 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
4431 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
4432 if (dataModelResponse.isRight()) {
4433 StorageOperationStatus storageStatus = dataModelResponse.right().value();
4434 BeEcompErrorManager.getInstance()
4435 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
4436 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4437 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
4438 log.trace("audit before sending response");
4439 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4440 return Either.right(responseFormat);
4443 if (!dataModelResponse.left().value()) {
4444 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
4445 currentTemplateName);
4446 ResponseFormat responseFormat = componentsUtils
4447 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
4448 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
4450 return Either.right(responseFormat);
4453 return Either.left(true);
4456 public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
4457 log.debug("validate resource derivedFrom field");
4458 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
4459 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
4460 log.info("derived from (template) field is missing for the resource");
4461 ResponseFormat responseFormat = componentsUtils
4462 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4463 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4465 throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
4469 private void validateResourceNameUniqueness(Resource resource) {
4471 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
4472 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
4473 resource.getComponentType());
4474 if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
4475 log.debug("resource with name: {}, already exists", resource.getName());
4476 throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
4477 resource.getName());
4478 } else if(resourceOperationResponse.isRight()){
4479 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
4480 throw new StorageException(resourceOperationResponse.right().value());
4485 private void validateCategory(User user, Resource resource,
4486 AuditingActionEnum actionEnum, boolean inTransaction) {
4488 List<CategoryDefinition> categories = resource.getCategories();
4489 if (CollectionUtils.isEmpty(categories)) {
4490 log.debug(CATEGORY_IS_EMPTY);
4491 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4492 ComponentTypeEnum.RESOURCE.getValue());
4493 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4494 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4495 ComponentTypeEnum.RESOURCE.getValue());
4497 if (categories.size() > 1) {
4498 log.debug("Must be only one category for resource");
4499 throw new ComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
4501 CategoryDefinition category = categories.get(0);
4502 List<SubCategoryDefinition> subcategories = category.getSubcategories();
4503 if (CollectionUtils.isEmpty(subcategories)) {
4504 log.debug("Missinig subcategory for resource");
4505 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
4507 if (subcategories.size() > 1) {
4508 log.debug("Must be only one sub category for resource");
4509 throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
4512 SubCategoryDefinition subcategory = subcategories.get(0);
4514 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
4515 log.debug(CATEGORY_IS_EMPTY);
4516 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
4517 ComponentTypeEnum.RESOURCE.getValue());
4518 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4519 throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
4520 ComponentTypeEnum.RESOURCE.getValue());
4522 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
4523 log.debug(CATEGORY_IS_EMPTY);
4524 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4525 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4526 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4527 throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
4530 validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
4533 private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
4534 User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4535 ResponseFormat responseFormat;
4536 if (category != null && subcategory != null) {
4537 log.debug("validating resource category {} against valid categories list", category);
4538 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
4539 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
4540 if (categories.isRight()) {
4541 log.debug("failed to retrive resource categories from Titan");
4542 responseFormat = componentsUtils.getResponseFormat(categories.right().value());
4543 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4544 throw new ComponentException(categories.right().value());
4546 List<CategoryDefinition> categoryList = categories.left().value();
4547 Optional<CategoryDefinition> foundCategory = categoryList.stream()
4548 .filter(cat -> cat.getName().equals(category.getName()))
4550 if(!foundCategory.isPresent()){
4551 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
4552 category, categoryList);
4553 failOnInvalidCategory(user, resource, actionEnum);
4555 Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
4558 .filter(subcat -> subcat.getName().equals(subcategory.getName()))
4560 if(!foundSubcategory.isPresent()){
4561 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
4562 subcategory, foundCategory.get().getSubcategories());
4563 failOnInvalidCategory(user, resource, actionEnum);
4568 private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
4569 ResponseFormat responseFormat;
4570 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
4571 ComponentTypeEnum.RESOURCE.getValue());
4572 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4573 throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
4574 ComponentTypeEnum.RESOURCE.getValue());
4577 public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
4578 String vendorRelease = resource.getVendorRelease();
4579 log.debug("validate vendor relese name");
4580 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
4581 log.info("vendor relese name is missing.");
4582 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
4583 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4584 throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
4587 validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
4590 public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
4591 if (vendorRelease != null) {
4592 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
4593 log.info("vendor release exceds limit.");
4594 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4595 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4596 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4597 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
4600 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
4601 log.info("vendor release is not valid.");
4602 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
4603 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4604 throw new ComponentException(ActionStatus.INVALID_VENDOR_RELEASE);
4609 private void validateVendorName(User user, Resource resource,
4610 AuditingActionEnum actionEnum) {
4611 String vendorName = resource.getVendorName();
4612 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
4613 log.info("vendor name is missing.");
4614 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
4615 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4616 throw new ComponentException(ActionStatus.MISSING_VENDOR_NAME);
4618 validateVendorName(vendorName, user, resource, actionEnum);
4621 private void validateVendorName(String vendorName, User user, Resource resource,
4622 AuditingActionEnum actionEnum) {
4623 if (vendorName != null) {
4624 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
4625 log.info("vendor name exceds limit.");
4626 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4627 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4628 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4629 throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
4630 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
4633 if (!ValidationUtils.validateVendorName(vendorName)) {
4634 log.info("vendor name is not valid.");
4635 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
4636 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4637 throw new ComponentException(ActionStatus.INVALID_VENDOR_NAME);
4642 private void validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
4643 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
4644 if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
4645 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
4646 log.info("resource vendor model number exceeds limit.");
4647 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
4648 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4649 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4650 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4651 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
4652 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
4654 // resource vendor model number is currently validated as vendor
4656 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
4657 log.info("resource vendor model number is not valid.");
4658 ResponseFormat errorResponse = componentsUtils
4659 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4660 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4661 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
4667 private void validateCost(Resource resource) {
4668 String cost = resource.getCost();
4670 if (!ValidationUtils.validateCost(cost)) {
4671 log.debug("resource cost is invalid.");
4672 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4677 private void validateLicenseType(User user, Resource resource,
4678 AuditingActionEnum actionEnum) {
4679 log.debug("validate licenseType");
4680 String licenseType = resource.getLicenseType();
4681 if (licenseType != null) {
4682 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
4684 if (!licenseTypes.contains(licenseType)) {
4685 log.debug("License type {} isn't configured", licenseType);
4686 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4687 if (actionEnum != null) {
4688 // In update case, no audit is required
4689 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4691 throw new ComponentException(ActionStatus.INVALID_CONTENT);
4696 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
4697 Resource updatedResource, String userId, boolean inTransaction) {
4698 Either<Operation, ResponseFormat> deleteArtifactByInterface;
4699 if (updatedResource.getDerivedFrom() != null) {
4700 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
4701 log.debug("1. Removing interface artifacts from graph");
4702 // Remove all interface artifacts of resource
4703 String resourceId = updatedResource.getUniqueId();
4704 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
4706 if (interfaces != null) {
4707 Collection<InterfaceDefinition> values = interfaces.values();
4708 for (InterfaceDefinition interfaceDefinition : values) {
4709 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
4711 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
4712 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
4713 if (operations != null) {
4714 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
4715 Operation operation = operationEntry.getValue();
4716 ArtifactDefinition implementation = operation.getImplementationArtifact();
4717 if (implementation != null) {
4718 String uniqueId = implementation.getUniqueId();
4719 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
4720 uniqueId, operationEntry.getKey(), interfaceType);
4721 // only thing that transacts and locks here
4722 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
4725 if (deleteArtifactByInterface.isRight()) {
4726 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
4727 if (!inTransaction) {
4728 titanDao.rollback();
4730 return Either.right(deleteArtifactByInterface.right().value());
4733 log.trace("No implementation found for operation {} - nothing to delete",
4734 operationEntry.getKey());
4738 log.trace("No operations found for interface type {}", interfaceType);
4742 log.debug("2. Removing properties");
4743 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
4744 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
4746 if (findPropertiesOfNode.isRight()
4747 && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
4748 log.debug("Failed to remove all properties of resource");
4749 if (!inTransaction) {
4750 titanDao.rollback();
4752 return Either.right(componentsUtils.getResponseFormat(
4753 componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
4757 log.debug("Derived from wasn't changed during update");
4760 if (inTransaction) {
4761 return Either.left(true);
4764 return Either.left(true);
4768 /**** Auditing *******************/
4770 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
4771 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
4772 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
4774 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
4776 return webApplicationContext.getBean(class1);
4779 public ICapabilityTypeOperation getCapabilityTypeOperation() {
4780 return capabilityTypeOperation;
4783 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
4784 this.capabilityTypeOperation = capabilityTypeOperation;
4787 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
4788 log.debug("validate resource properties default values");
4789 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4790 List<PropertyDefinition> properties = resource.getProperties();
4791 if (properties != null) {
4792 eitherResult = iterateOverProperties(properties);
4794 return eitherResult;
4797 public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
4798 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4800 String innerType = null;
4801 for (PropertyDefinition property : properties) {
4802 if (!propertyOperation.isPropertyTypeValid(property)) {
4803 log.info("Invalid type for property {}", property);
4804 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
4805 ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
4806 eitherResult = Either.right(responseFormat);
4810 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
4811 applicationDataTypeCache);
4812 if (allDataTypes.isRight()) {
4813 return Either.right(allDataTypes.right().value());
4816 type = property.getType();
4818 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4819 ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes.left().value());
4820 if(responseFormat != null) {
4824 eitherResult = validateDefaultPropertyValue(property, allDataTypes.left().value(), type, innerType);
4826 return eitherResult;
4829 private Either<Boolean,ResponseFormat> validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
4830 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
4831 log.info("Invalid default value for property {}", property);
4832 ResponseFormat responseFormat;
4833 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
4834 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
4835 property.getName(), type, innerType, property.getDefaultValue());
4837 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
4838 property.getName(), type, property.getDefaultValue());
4840 return Either.right(responseFormat);
4843 return Either.left(true);
4846 private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
4847 ResponseFormat responseFormat = null;
4848 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
4849 .isPropertyInnerTypeValid(property, allDataTypes);
4850 innerType = propertyInnerTypeValid.getLeft();
4851 if (!propertyInnerTypeValid.getRight().booleanValue()) {
4852 log.info("Invalid inner type for property {}", property);
4853 responseFormat = componentsUtils.getResponseFormat(
4854 ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
4856 return responseFormat;
4860 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
4861 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
4865 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
4866 return componentInstanceBusinessLogic;
4869 private String getComponentTypeForResponse(Component component) {
4870 String componentTypeForResponse = "SERVICE";
4871 if (component instanceof Resource) {
4872 componentTypeForResponse = ((Resource) component).getResourceType().name();
4874 return componentTypeForResponse;
4877 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
4880 validateUserExists(user, "Get resource from csar UUID",
4883 // get resource from csar uuid
4884 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
4885 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
4886 if (either.isRight()) {
4887 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
4889 return Either.right(resp);
4892 return Either.left(either.left().value());
4896 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
4897 String componentId, String userId) {
4901 private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
4902 String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
4903 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4905 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
4906 uploadedCapabilities.forEach((k,v)->addValidComponentInstanceCapabilities(k,v,resourceId,defaultCapabilities,validCapabilitiesMap));
4907 return validCapabilitiesMap;
4910 private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<CapabilityDefinition>> validCapabilitiesMap){
4911 String capabilityType = capabilities.get(0).getType();
4912 if (defaultCapabilities.containsKey(capabilityType)) {
4913 CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
4914 validateCapabilityProperties(capabilities, resourceId, defaultCapability);
4915 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
4916 validCapabilityList.add(defaultCapability);
4917 validCapabilitiesMap.put(key, validCapabilityList);
4919 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType));
4923 private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
4924 if (CollectionUtils.isEmpty(defaultCapability.getProperties())
4925 && isNotEmpty(capabilities.get(0).getProperties())) {
4926 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
4927 defaultCapability.getName(), resourceId);
4929 "Failed to update capability property values. Property list of fetched capability {} is empty. ",
4930 defaultCapability.getName());
4931 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
4932 } else if (isNotEmpty(capabilities.get(0).getProperties())) {
4933 validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
4937 private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
4938 CapabilityDefinition defaultCapability;
4939 if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
4940 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
4942 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
4943 .getToscaFullElement(resourceId);
4944 if (getFullComponentRes.isRight()) {
4945 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
4946 getFullComponentRes.right().value());
4947 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
4950 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
4952 return defaultCapability;
4955 private void validateUniquenessUpdateUploadedComponentInstanceCapability(
4956 CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
4957 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
4958 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
4959 .collect(toMap(PropertyDefinition::getName, Function.identity()));
4960 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
4961 for (UploadPropInfo property : uploadedProperties) {
4962 String propertyName = property.getName().toLowerCase();
4963 String propertyType = property.getType();
4964 ComponentInstanceProperty validProperty;
4965 if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
4966 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
4969 validProperty = new ComponentInstanceProperty();
4970 validProperty.setName(propertyName);
4971 if (property.getValue() != null) {
4972 validProperty.setValue(property.getValue().toString());
4974 validProperty.setDescription(property.getDescription());
4975 validProperty.setPassword(property.isPassword());
4976 validProperties.add(validProperty);
4978 defaultCapability.setProperties(validProperties);
4981 private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
4982 return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
4985 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
4986 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
4987 Resource resource, User user) {
4989 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
4990 ArtifactOperationEnum.class);
4991 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
4992 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
4993 .left(nodeTypeArtifactsToHandle);
4995 // add all found Csar artifacts to list to upload
4996 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
4997 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
4998 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
4999 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
5000 ArtifactDefinition foundArtifact;
5002 if (!existingArtifactsToHandle.isEmpty()) {
5003 foundArtifact = existingArtifactsToHandle.stream()
5004 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
5006 if (foundArtifact != null) {
5007 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
5008 .getArtifactType()) {
5009 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
5010 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
5011 // if current artifact already exists, but has
5012 // different content, add him to the list to
5014 artifactsToUpdate.add(currNewArtifact);
5016 // remove found artifact from the list of existing
5017 // artifacts to handle, because it was already
5019 existingArtifactsToHandle.remove(foundArtifact);
5020 // and remove found artifact from the list to
5021 // upload, because it should either be updated or be
5023 artifactsToUpload.remove(currNewArtifact);
5025 log.debug("Can't upload two artifact with the same name {}.",
5026 currNewArtifact.getArtifactName());
5027 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
5028 ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
5029 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
5030 foundArtifact.getArtifactType());
5031 AuditingActionEnum auditingAction = artifactsBusinessLogic
5032 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
5033 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
5034 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
5035 user, null, null, foundArtifact.getUniqueId(), responseFormat,
5036 resource.getComponentType(), null);
5037 responseWrapper.setInnerElement(responseFormat);
5043 if (responseWrapper.isEmpty()) {
5044 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
5045 if (currArtifact.getIsFromCsar()) {
5046 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5048 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
5053 if (responseWrapper.isEmpty()) {
5054 if (!artifactsToUpload.isEmpty()) {
5055 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
5057 if (!artifactsToUpdate.isEmpty()) {
5058 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
5060 if (!artifactsToDelete.isEmpty()) {
5061 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
5064 if (!responseWrapper.isEmpty()) {
5065 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
5067 } catch (Exception e) {
5068 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5069 responseWrapper.setInnerElement(responseFormat);
5070 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
5072 return nodeTypeArtifactsToHandleRes;
5075 ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
5076 String nodeTypeFullName) {
5078 String actualVfName;
5079 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
5080 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
5081 actualType = ResourceTypeEnum.VFC.name();
5083 actualVfName = vfResourceName;
5084 actualType = nodeResourceType;
5087 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
5088 String nameWithouNamespacePrefix = nodeTypeFullName
5089 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
5090 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
5091 String resourceType = findTypes[0];
5092 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
5094 if (actualName.startsWith(Constants.ABSTRACT)) {
5095 toscaResourceName.append(resourceType.toLowerCase()).append('.')
5096 .append(ValidationUtils.convertToSystemName(actualVfName));
5098 toscaResourceName.append(actualType.toLowerCase()).append('.')
5099 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
5101 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
5102 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
5103 previousToscaResourceName
5104 .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
5108 public ICacheMangerOperation getCacheManagerOperation() {
5109 return cacheManagerOperation;
5112 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
5113 this.cacheManagerOperation = cacheManagerOperation;
5117 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
5119 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
5120 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
5123 if (resourceResultEither.isRight()) {
5124 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5125 log.debug("Failed to found resource with id {} ", resourceId);
5126 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
5129 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
5130 return Either.right(componentsUtils.getResponseFormatByResource(
5131 componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
5134 Resource resource = resourceResultEither.left().value();
5135 UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
5136 dataParamsToReturn);
5137 return Either.left(dataTransfer);
5141 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
5142 Resource resource = (Resource) clonedComponent;
5143 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
5144 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
5145 .shouldUpgradeToLatestDerived(resource);
5146 if (shouldUpgradeToLatestDerived.isRight()) {
5147 return Either.right(
5148 componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
5150 return Either.left(shouldUpgradeToLatestDerived.left().value());
5152 return super.shouldUpgradeToLatestDerived(clonedComponent);