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 com.google.gson.Gson;
25 import fj.data.Either;
26 import org.apache.commons.codec.binary.Base64;
27 import org.apache.commons.collections.CollectionUtils;
28 import org.apache.commons.collections.MapUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.commons.lang3.tuple.ImmutablePair;
31 import org.openecomp.sdc.be.components.csar.CsarArtifactsAndGroupsBusinessLogic;
32 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
33 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
34 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
36 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
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.MergeResourceBLFactory;
41 import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic;
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.CapabilityDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
53 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
54 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
56 import org.openecomp.sdc.be.impl.ComponentsUtils;
57 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
58 import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
59 import org.openecomp.sdc.be.model.ArtifactDefinition;
60 import org.openecomp.sdc.be.model.CapabilityDefinition;
61 import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
62 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
63 import org.openecomp.sdc.be.model.Component;
64 import org.openecomp.sdc.be.model.ComponentInstance;
65 import org.openecomp.sdc.be.model.ComponentInstanceInput;
66 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
67 import org.openecomp.sdc.be.model.ComponentParametersView;
68 import org.openecomp.sdc.be.model.CsarInfo;
69 import org.openecomp.sdc.be.model.DataTypeDefinition;
70 import org.openecomp.sdc.be.model.GroupDefinition;
71 import org.openecomp.sdc.be.model.GroupProperty;
72 import org.openecomp.sdc.be.model.GroupTypeDefinition;
73 import org.openecomp.sdc.be.model.InputDefinition;
74 import org.openecomp.sdc.be.model.InterfaceDefinition;
75 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
76 import org.openecomp.sdc.be.model.LifecycleStateEnum;
77 import org.openecomp.sdc.be.model.NodeTypeInfo;
78 import org.openecomp.sdc.be.model.Operation;
79 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
80 import org.openecomp.sdc.be.model.PropertyDefinition;
81 import org.openecomp.sdc.be.model.RelationshipImpl;
82 import org.openecomp.sdc.be.model.RelationshipInfo;
83 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
84 import org.openecomp.sdc.be.model.RequirementDefinition;
85 import org.openecomp.sdc.be.model.Resource;
86 import org.openecomp.sdc.be.model.UploadCapInfo;
87 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
88 import org.openecomp.sdc.be.model.UploadPropInfo;
89 import org.openecomp.sdc.be.model.UploadReqInfo;
90 import org.openecomp.sdc.be.model.UploadResourceInfo;
91 import org.openecomp.sdc.be.model.User;
92 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
93 import org.openecomp.sdc.be.model.category.CategoryDefinition;
94 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
95 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
96 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
97 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
98 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
99 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
100 import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
101 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
102 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
103 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
104 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
105 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
106 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
107 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
108 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
109 import org.openecomp.sdc.be.tosca.CsarUtils;
110 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
111 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
112 import org.openecomp.sdc.be.user.IUserBusinessLogic;
113 import org.openecomp.sdc.be.user.Role;
114 import org.openecomp.sdc.be.user.UserBusinessLogic;
115 import org.openecomp.sdc.be.utils.CommonBeUtils;
116 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
117 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
118 import org.openecomp.sdc.common.api.Constants;
119 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
120 import org.openecomp.sdc.common.datastructure.Wrapper;
121 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
122 import org.openecomp.sdc.common.util.GeneralUtility;
123 import org.openecomp.sdc.common.util.ValidationUtils;
124 import org.openecomp.sdc.exception.ResponseFormat;
125 import org.slf4j.Logger;
126 import org.slf4j.LoggerFactory;
127 import org.springframework.beans.factory.annotation.Autowired;
128 import org.springframework.web.context.WebApplicationContext;
129 import org.yaml.snakeyaml.DumperOptions;
130 import org.yaml.snakeyaml.Yaml;
131 import org.yaml.snakeyaml.parser.ParserException;
133 import javax.servlet.ServletContext;
135 import java.util.Map.Entry;
136 import java.util.function.Function;
137 import java.util.regex.Matcher;
138 import java.util.regex.Pattern;
139 import java.util.stream.Collectors;
141 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
143 @org.springframework.stereotype.Component("resourceBusinessLogic")
144 public class ResourceBusinessLogic extends ComponentBusinessLogic {
146 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
147 public static final String INITIAL_VERSION = "0.1";
149 private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
150 private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
151 private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
152 private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
153 private Pattern GET_ATTRIBUTE_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_attribute" + "=");
155 private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class);
157 private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
160 * Default constructor
162 public ResourceBusinessLogic() {
163 log.debug("ResourceBusinessLogic started");
167 private ICapabilityTypeOperation capabilityTypeOperation = null;
170 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
173 private LifecycleBusinessLogic lifecycleBusinessLogic;
176 private IPropertyOperation propertyOperation;
179 private CsarOperation csarOperation;
182 private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
185 private ResourceImportManager resourceImportManager;
189 private InputsBusinessLogic inputsBusinessLogic;
192 private CompositionBusinessLogic compositionBusinessLogic;
195 private ICacheMangerOperation cacheManagerOperation;
198 private ApplicationDataTypeCache dataTypeCache;
201 private MergeResourceBLFactory mergeResourceBLFactory;
204 private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
206 private Gson gson = new Gson();
208 public CsarOperation getCsarOperation() {
209 return csarOperation;
212 public void setCsarOperation(CsarOperation csarOperation) {
213 this.csarOperation = csarOperation;
216 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
217 return lifecycleBusinessLogic;
220 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
221 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
224 public IElementOperation getElementDao() {
228 public void setElementDao(IElementOperation elementDao) {
229 this.elementDao = elementDao;
232 public IUserBusinessLogic getUserAdmin() {
233 return this.userAdmin;
236 public void setUserAdmin(UserBusinessLogic userAdmin) {
237 this.userAdmin = userAdmin;
240 public ComponentsUtils getComponentsUtils() {
241 return this.componentsUtils;
244 public void setComponentsUtils(ComponentsUtils componentsUtils) {
245 this.componentsUtils = componentsUtils;
248 public ArtifactsBusinessLogic getArtifactsManager() {
249 return artifactsBusinessLogic;
252 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
253 this.artifactsBusinessLogic = artifactsManager;
256 public void setPropertyOperation(IPropertyOperation propertyOperation) {
257 this.propertyOperation = propertyOperation;
260 public ApplicationDataTypeCache getApplicationDataTypeCache() {
261 return applicationDataTypeCache;
264 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
265 this.applicationDataTypeCache = applicationDataTypeCache;
269 * the method returns a list of all the resources that are certified, the
270 * returned resources are only abstract or only none abstract according to
277 public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract,
278 HighestFilterEnum highestFilter, String userId) {
279 Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
280 if (resp.isRight()) {
281 return Either.right(resp.right().value());
283 Boolean isHighest = null;
284 switch (highestFilter) {
290 case NON_HIGHEST_ONLY:
296 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
297 .getAllCertifiedResources(getAbstract, isHighest);
299 if (getResponse.isRight()) {
300 return Either.right(componentsUtils
301 .getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
304 return Either.left(getResponse.left().value());
307 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
308 ResourceTypeEnum resourceTypeEnum, String userId) {
310 Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
311 if (resp.isRight()) {
312 return Either.right(resp.right().value());
315 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
316 .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
320 if (dataModelResponse.isLeft()) {
321 Map<String, Boolean> result = new HashMap<>();
322 result.put("isValid", dataModelResponse.left().value());
323 log.debug("validation was successfully performed.");
324 return Either.left(result);
327 ResponseFormat responseFormat = componentsUtils
328 .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
330 return Either.right(responseFormat);
333 public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction,
334 User user, Map<String, byte[]> csarUIPayload, String payloadName) {
335 Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
336 if (createResourceResponse.isRight()) {
337 return createResourceResponse;
340 // Creating resource either by DAO or from CSAR
341 String csarUUID = null;
342 if (payloadName == null) {
343 csarUUID = resource.getCsarUUID();
345 csarUUID = payloadName;
347 if (csarUUID != null && !csarUUID.isEmpty()) {
348 // check if VF with the same Csar UUID or with he same name already
350 Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade
351 .validateCsarUuidUniqueness(csarUUID);
352 if (validateCsarUuidUniquenessRes.isRight()) {
353 log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID,
354 resource.getSystemName());
355 return Either.right(componentsUtils.getResponseFormat(
356 componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
359 Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
360 if (existingResourceRes.intValue() > 0) {
361 log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ",
362 resource.getSystemName(), csarUUID);
363 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS,
365 componentsUtils.auditResource(errorResponse, user, resource, auditingAction);
366 return Either.right(errorResponse);
369 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
370 createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
371 return createResourceResponse;
374 return createResourceByDao(resource, user, auditingAction, false, false);
377 public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user,
378 Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
379 Either<Resource, ResponseFormat> updateResourceResponse = null;
380 Either<Resource, ResponseFormat> validateResourceResponse = null;
381 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
382 String csarUUID = null;
383 String csarVersion = null;
384 if (payloadName == null) {
385 csarUUID = resource.getCsarUUID();
386 csarVersion = resource.getCsarVersion();
388 csarUUID = payloadName;
390 if (csarUUID != null && !csarUUID.isEmpty()) {
391 Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
392 if (responseWrapper.isEmpty()) {
393 validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
395 if (responseWrapper.isEmpty()) {
396 validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
398 if (responseWrapper.isEmpty()) {
399 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
400 overrideImmutableMetadata(oldResource, resource);
402 validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
403 if (validateResourceResponse.isRight()) {
404 responseWrapper.setInnerElement(validateResourceResponse.right().value());
407 if (responseWrapper.isEmpty()) {
408 String oldCsarVersion = oldResource.getCsarVersion();
409 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
411 // (on boarding flow): If the update includes same csarUUID and
412 // same csarVersion as already in the VF - no need to import the
413 // csar (do only metadata changes if there are).
414 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
415 updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
418 updateResourceResponse = updateResourceFromCsar(oldResource, resource, user,
419 AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
423 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
424 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
426 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
427 responseWrapper.setInnerElement(errorResponse);
429 if (responseWrapper.isEmpty()) {
430 return updateResourceResponse;
432 return Either.right(responseWrapper.getInnerElement());
435 private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource,
436 Resource resource, String csarUUID, User user) {
437 // (on boarding flow): If the update includes a csarUUID: verify this
438 // csarUUID is not in use by another VF, If it is - use same error as
440 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
441 // select another or update the existing VF." %1 - csarUUID, %2 - VF
443 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
444 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
445 if (resourceLinkedToCsarRes.isRight()) {
446 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
447 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
448 resource.getSystemName());
449 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(
450 componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
452 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
453 && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
454 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
455 resourceLinkedToCsarRes.left().value().getName());
456 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
457 responseWrapper.setInnerElement(errorResponse);
461 private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource,
462 Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
463 // (on boarding flow): If the update includes csarUUID which is
464 // different from the csarUUID of the VF - fail with
465 // error: "Error: Resource %1 cannot be updated using since it is linked
466 // to a different VSP" %1 - VF name
467 String oldCsarUUID = oldResource.getCsarUUID();
468 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
470 "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
471 resourceUniqueId, csarUUID, oldCsarUUID);
472 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
473 ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
474 componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
475 responseWrapper.setInnerElement(errorResponse);
479 private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
480 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
481 if (oldResourceRes.isRight()) {
482 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
483 oldResourceRes.right().value());
484 responseWrapper.setInnerElement(componentsUtils
485 .getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
488 return oldResourceRes.left().value();
491 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
492 resource.setName(oldRresource.getName());
493 resource.setIcon(oldRresource.getIcon());
494 resource.setTags(oldRresource.getTags());
495 resource.setVendorName(oldRresource.getVendorName());
496 resource.setCategories(oldRresource.getCategories());
497 resource.setDerivedFrom(oldRresource.getDerivedFrom());
500 private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource,
501 User user, AuditingActionEnum updateResource, boolean inTransaction,
502 Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
505 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
506 if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
507 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}",
508 oldRresource.getLastUpdaterUserId(), user.getUserId());
509 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
512 String lockedResourceId = oldRresource.getUniqueId();
513 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
515 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
516 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
517 csar = csarUIPayload;
519 csar = csarOperation.getCsar(csarUUID, user);
521 if (csar.isRight()) {
522 log.debug("Failed to get csar for casrUUID{} ", csarUUID);
523 return Either.right(componentsUtils
524 .getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
527 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource,
528 user, csarUUID, csar);
529 if (toscaYamlCsarStatus.isRight()) {
530 return Either.right(toscaYamlCsarStatus.right().value());
532 Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(),
533 csarUUID, componentsUtils);
534 if (checksum.isRight()) {
535 log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
536 return Either.right(checksum.right().value());
538 if (!checksum.left().value().equals(
539 oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
540 log.debug("The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.", csarUUID,
541 oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition()
542 .getImportedToscaChecksum(),
543 checksum.left().value());
544 oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition()
545 .setImportedToscaChecksum(checksum.left().value());
548 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource,
549 "update Resource From Csar");
550 if (lockResult.isRight()) {
551 return Either.right(lockResult.right().value());
554 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
555 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
556 CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents,
558 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
559 Either<Resource, ResponseFormat> result = null;
561 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
562 nodeTypesInfo, csarInfo, oldRresource);
563 if (findNodeTypesArtifactsToHandleRes.isRight()) {
564 log.debug("failed to find node types for update with artifacts during import csar {}. ",
565 csarInfo.getCsarUUID());
566 result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
569 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
572 result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, yamlFileName,
573 yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
576 if (result == null || result.isRight()) {
577 log.warn("operation failed. do rollback");
580 log.debug("operation success. do commit");
583 log.debug("unlock resource {}", lockedResourceId);
584 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
590 private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource,
591 AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts,
592 String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
593 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
594 String nodeName, boolean isNested) {
595 Either<Resource, ResponseFormat> result;
596 Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither;
597 boolean inTransaction = true;
598 boolean shouldLock = false;
600 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate;
601 Resource preparedResource;
602 Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(
603 yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(),
604 nodeTypesInfo, nodeName);
605 if (uploadComponentInstanceInfoMap.isRight()) {
606 ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
607 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, updateResource);
608 result = Either.right(responseFormat);
612 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value()
615 prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
616 inTransaction, shouldLock, isNested);
617 if (prepareForUpdate.isRight()) {
618 log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
619 result = Either.right(prepareForUpdate.right().value());
622 preparedResource = prepareForUpdate.left().value().left;
624 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
626 Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(preparedResource);
627 if (genericResourceEither.isRight()) {
628 log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value());
629 ResponseFormat responseFormat = genericResourceEither.right().value();
630 componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(),
631 preparedResource, updateResource);
632 return Either.right(responseFormat);
635 parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
636 shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
637 if (parseNodeTypeInfoYamlEither.isRight()) {
638 ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
639 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, updateResource);
640 result = Either.right(responseFormat);
644 Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
645 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource,
646 csarInfo.getModifier(), inputs, inTransaction);
647 if (createInputsOnResource.isRight()) {
648 log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
649 ResponseFormat responseFormat = createInputsOnResource.right().value();
650 componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(),
651 preparedResource, updateResource);
652 result = Either.right(responseFormat);
655 preparedResource = createInputsOnResource.left().value();
657 Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(
658 csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock,
659 csarInfo.getCreatedNodes());
660 if (createResourcesInstancesEither.isRight()) {
661 log.debug("failed to create resource instances status is {}",
662 createResourcesInstancesEither.right().value());
663 ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
664 componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(),
665 preparedResource, updateResource);
666 result = Either.right(responseFormat);
669 preparedResource = createResourcesInstancesEither.left().value();
671 createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName,
672 preparedResource, instances);
673 if (createResourcesInstancesEither.isRight()) {
674 log.debug("failed to create relation between resource instances status is {}",
675 createResourcesInstancesEither.right().value());
676 result = Either.right(createResourcesInstancesEither.right().value());
680 preparedResource = createResourcesInstancesEither.left().value();
682 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
683 .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(),
684 preparedResource.getSystemName());
685 if (validateUpdateVfGroupNamesRes.isRight()) {
687 return Either.right(validateUpdateVfGroupNamesRes.right().value());
689 // add groups to resource
690 Map<String, GroupDefinition> groups;
692 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
693 groups = validateUpdateVfGroupNamesRes.left().value();
695 groups = uploadComponentInstanceInfoMap.left().value().getGroups();
697 Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource,
698 csarInfo.getModifier(), groups);
699 if (updatedGroupsOnResource.isRight()) {
701 return updatedGroupsOnResource;
703 preparedResource = updatedGroupsOnResource.left().value();
705 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
706 nodeTypesArtifactsToHandle);
708 Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
709 csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
710 if (updateArtifactsEither.isRight()) {
711 log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
712 result = Either.right(updateArtifactsEither.right().value());
715 preparedResource = updateArtifactsEither.left().value();
717 ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource);
718 if (mergingPropsAndInputsStatus != ActionStatus.OK) {
719 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
721 return Either.right(responseFormat);
724 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic
725 .setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
726 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value())
727 : Either.left(preparedResource);
733 private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
734 String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
735 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
737 String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
738 Resource resource = preparedResource;
740 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
741 .getNodeTypesArtifactsToHandle();
742 if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
743 if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
744 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
745 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
746 if (handleNodeTypeArtifactsRes.isRight()) {
747 return Either.right(handleNodeTypeArtifactsRes.right().value());
751 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
752 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
753 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
754 if (createdCsarArtifactsEither.isRight()) {
755 return createdCsarArtifactsEither;
758 resource = createdCsarArtifactsEither.left().value();
760 return Either.left(resource);
763 private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) {
764 Either<MergeResourceBusinessLogic, ActionStatus> mergeResourceBLEither = mergeResourceBLFactory
765 .getInstance(oldResource, newResource);
766 if (mergeResourceBLEither.isRight()) {
767 return mergeResourceBLEither.right().value();
769 MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value();
770 return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource);
773 private Either<Resource, ResponseFormat> handleResourceGenericType(Resource resource) {
774 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
775 if (genericResourceEither.isRight()) {
776 return genericResourceEither;
778 if (resource.shouldGenerateInputs()) {
779 generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
781 return genericResourceEither;
784 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
785 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
787 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
788 .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
789 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
790 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
793 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
794 Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo,
795 oldResource.getName(), csarInfo);
796 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes;
797 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
798 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
799 oldResource.getName(), csarInfo.getCsarUUID());
801 for (Entry<String, ImmutablePair<String, String>> currVfcToscaNameEntry : extractedVfcToscaNames
803 String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft();
804 String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight();
805 String currNamespace = currVfcToscaNameEntry.getKey();
806 log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
808 Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade
809 .getLatestByToscaResourceName(currVfcToscaName);
810 Resource curNodeType = null;
811 if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
812 curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName);
814 if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
815 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName,
816 curVfcRes.right().value());
817 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
818 componentsUtils.convertFromStorageResponse(curVfcRes.right().value()),
819 csarInfo.getCsarUUID());
820 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, AuditingActionEnum.CREATE_RESOURCE);
821 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
823 } else if (curVfcRes.isLeft()) {
824 curNodeType = curVfcRes.left().value();
826 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
827 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
828 if (extractedVfcsArtifacts.containsKey(currNamespace)) {
829 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
831 curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
832 if (curNodeTypeArtifactsToHandleRes.isRight()) {
833 nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
836 curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
838 } else if (curNodeType != null) {
839 // delete all artifacts if have not received artifacts from
841 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
842 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
843 // delete all informational artifacts
844 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
845 .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
846 .collect(Collectors.toList()));
847 // delete all deployment artifacts
848 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
849 if (!artifactsToDelete.isEmpty()) {
850 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
853 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
854 nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
857 } catch (Exception e) {
858 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
859 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
860 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
862 return nodeTypesArtifactsToHandleRes;
865 private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(
866 Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
868 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
869 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
870 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
872 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
873 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
874 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
875 if (curNodeType != null) {
876 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
877 if (curNodeType.getDeploymentArtifacts() != null) {
878 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
880 if (curNodeType.getArtifacts() != null) {
882 .putAll(curNodeType.getArtifacts().entrySet().stream()
883 .filter(e -> e.getValue()
884 .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
885 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
887 for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
888 ArtifactDefinition foundArtifact;
890 if (!existingArtifacts.isEmpty()) {
891 foundArtifact = existingArtifacts.values().stream()
892 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
894 if (foundArtifact != null) {
895 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
896 if (!foundArtifact.getArtifactChecksum()
897 .equals(currNewArtifact.getArtifactChecksum())) {
898 foundArtifact.setPayload(currNewArtifact.getPayloadData());
899 foundArtifact.setPayloadData(
900 Base64.encodeBase64String(currNewArtifact.getPayloadData()));
901 foundArtifact.setArtifactChecksum(GeneralUtility
902 .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
903 artifactsToUpdate.add(foundArtifact);
905 existingArtifacts.remove(foundArtifact.getArtifactLabel());
906 artifactsToUpload.remove(currNewArtifact);
908 log.debug("Can't upload two artifact with the same name {}.",
909 currNewArtifact.getArtifactName());
910 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
911 ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
912 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
913 foundArtifact.getArtifactType());
914 responseWrapper.setInnerElement(responseFormat);
920 if (responseWrapper.isEmpty()) {
921 artifactsToDelete.addAll(existingArtifacts.values());
924 if (responseWrapper.isEmpty()) {
925 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
926 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
927 if (!artifactsToUpload.isEmpty())
928 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
929 if (!artifactsToUpdate.isEmpty())
930 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
931 if (!artifactsToDelete.isEmpty())
932 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
934 nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
936 if (!responseWrapper.isEmpty()) {
937 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
939 } catch (Exception e) {
940 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
941 responseWrapper.setInnerElement(responseFormat);
942 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
944 return nodeTypeArtifactsToHandleRes;
948 * Changes resource life cycle state to checked out
952 * @param inTransaction
955 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
956 Either<Resource, ResponseFormat> checkoutResourceRes;
958 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
959 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
961 "************* Going to change life cycle state of resource {} to not certified checked out. ",
963 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
964 resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
965 new LifecycleChangeInfoWithAction("certification on import",
966 LifecycleChanceActionEnum.CREATE_FROM_CSAR),
967 inTransaction, true);
968 if (checkoutRes.isRight()) {
969 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
970 resource.getComponentType().getNodeType(), resource.getUniqueId(),
971 checkoutRes.right().value().getStatus());
972 checkoutResourceRes = Either.right(checkoutRes.right().value());
974 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
977 checkoutResourceRes = Either.left(resource);
979 } catch (Exception e) {
980 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
981 checkoutResourceRes = Either.right(responseFormat);
982 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
985 return checkoutResourceRes;
989 * Handles Artifacts of NodeType
991 * @param nodeTypeResource
992 * @param nodeTypeArtifactsToHandle
994 * @param inTransaction
997 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
998 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
999 List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
1000 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
1001 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
1002 Either<Resource, ResponseFormat> changeStateResponse;
1004 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
1005 if (changeStateResponse.isRight()) {
1006 return Either.right(changeStateResponse.right().value());
1008 nodeTypeResource = changeStateResponse.left().value();
1010 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
1011 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
1012 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
1014 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
1015 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
1016 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
1017 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
1018 nodeTypeResource.getName());
1019 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
1020 .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
1021 createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
1022 ignoreLifecycleState, curOperation),
1023 false, inTransaction);
1024 if (handleNodeTypeArtifactsRequestRes.isRight()) {
1025 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
1028 if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
1029 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
1031 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
1034 if (handleNodeTypeArtifactsRes == null) {
1035 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
1037 } catch (Exception e) {
1038 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1039 handleNodeTypeArtifactsRes = Either.right(responseFormat);
1040 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
1042 return handleNodeTypeArtifactsRes;
1045 private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
1046 String vfResourceName, CsarInfo csarInfo) {
1047 Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
1049 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
1050 if (!nodes.isEmpty()) {
1051 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
1052 while (nodesNameEntry.hasNext()) {
1053 Entry<String, Object> nodeType = nodesNameEntry.next();
1054 ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
1055 ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
1056 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
1059 for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
1060 vfcToscaNames.put(cvfc.getType(),
1061 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
1063 return vfcToscaNames;
1066 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1067 Map<String, Object> nodes = new HashMap<>();
1068 for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
1069 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
1071 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
1075 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
1076 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1077 .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
1078 if (eitherNodeTypes.isLeft()) {
1079 nodes.putAll(eitherNodeTypes.left().value());
1083 public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user,
1084 Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
1085 log.trace("************* created successfully from YAML, resource TOSCA ");
1087 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
1088 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
1089 csar = csarUIPayload;
1091 csar = csarOperation.getCsar(csarUUID, user);
1094 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user,
1096 if (toscaYamlCsarStatus.isRight()) {
1097 return Either.right(toscaYamlCsarStatus.right().value());
1099 Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(),
1100 csarUUID, componentsUtils);
1101 if (toscaYamlChecksum.isRight()) {
1102 log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID,
1103 toscaYamlChecksum.right().value());
1104 return Either.right(toscaYamlChecksum.right().value());
1106 resource.getComponentMetadataDefinition().getMetadataDataDefinition()
1107 .setImportedToscaChecksum(toscaYamlChecksum.left().value());
1109 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
1110 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
1111 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
1113 CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents,
1115 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
1116 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
1117 nodeTypesInfo, csarInfo, resource);
1118 if (findNodeTypesArtifactsToHandleRes.isRight()) {
1119 log.debug("failed to find node types for update with artifacts during import csar {}. ",
1120 csarInfo.getCsarUUID());
1121 return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
1123 Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents,
1124 yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
1126 if (createResourceFromYaml.isRight()) {
1127 log.debug("Couldn't create resource from YAML");
1128 return Either.right(createResourceFromYaml.right().value());
1131 Resource vfResource = createResourceFromYaml.left().value();
1132 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
1133 vfResource.getToscaResourceName());
1134 return Either.left(vfResource);
1137 private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) {
1138 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
1139 List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
1140 for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) {
1141 extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry);
1143 if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
1144 setDerivedFrom(nodeTypesInfo, globalSubstitutes);
1146 markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo);
1147 return nodeTypesInfo;
1150 @SuppressWarnings("unchecked")
1151 private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo,
1152 List<Entry<String, byte[]>> globalSubstitutes) {
1153 for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
1154 String yamlFileContents = new String(entry.getValue());
1155 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1156 Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate,
1157 ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
1158 if (nodeTypesEither.isLeft()) {
1159 Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
1160 for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
1161 Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
1162 if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
1163 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1164 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
1165 List<String> derivedFrom = new ArrayList<>();
1166 derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
1167 nodeTypeInfo.setDerivedFrom(derivedFrom);
1175 @SuppressWarnings("unchecked")
1176 private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
1177 List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) {
1178 if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
1179 if (!isGlobalSubstitute(entry.getKey())) {
1180 String yamlFileContents = new String(entry.getValue());
1181 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1182 Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(
1183 mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
1184 if (substitutionMappingsEither.isLeft()) {
1185 Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left()
1187 if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
1188 NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
1189 nodeTypeInfo.setType(
1190 (String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
1191 nodeTypeInfo.setTemplateFileName(entry.getKey());
1192 nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
1193 nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
1197 globalSubstitutes.add(entry);
1202 @SuppressWarnings("unchecked")
1203 private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
1204 Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate,
1205 ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
1206 if (nodeTemplatesEither.isLeft()) {
1207 Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
1208 for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
1209 Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
1210 if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
1211 String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
1212 if (nodeTypesInfo.containsKey(type)) {
1213 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
1214 nodeTypeInfo.setNested(true);
1221 private boolean isGlobalSubstitute(String fileName) {
1222 return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE)
1223 || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
1226 private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user,
1227 String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
1228 if (csar.isRight()) {
1229 StorageOperationStatus value = csar.right().value();
1230 log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
1231 BeEcompErrorManager.getInstance()
1232 .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1233 ResponseFormat responseFormat = componentsUtils
1234 .getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
1235 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
1236 return Either.right(responseFormat);
1239 Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(),
1240 csarUUID, componentsUtils);
1241 if (validateCsarStatus.isRight()) {
1242 ResponseFormat responseFormat = validateCsarStatus.right().value();
1243 log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
1244 BeEcompErrorManager.getInstance()
1245 .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1246 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
1247 return Either.right(responseFormat);
1250 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils
1251 .getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
1253 if (toscaYamlCsarStatus.isRight()) {
1254 ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
1255 log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
1256 BeEcompErrorManager.getInstance()
1257 .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1258 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
1259 return Either.right(responseFormat);
1261 return toscaYamlCsarStatus;
1264 private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user,
1265 boolean inTransaction) {
1266 log.trace("validating resource before create");
1267 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource,
1268 AuditingActionEnum.CREATE_RESOURCE, false);
1269 if (eitherCreator.isRight()) {
1270 return Either.right(eitherCreator.right().value());
1272 user.copyData(eitherCreator.left().value());
1274 // validate user role
1275 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(),
1276 AuditingActionEnum.CREATE_RESOURCE, null);
1277 if (validateRes.isRight()) {
1278 return Either.right(validateRes.right().value());
1280 // VF / PNF "derivedFrom" should be null (or ignored)
1281 if (ModelConverter.isAtomicComponent(resource)) {
1282 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource,
1283 AuditingActionEnum.CREATE_RESOURCE);
1284 if (validateDerivedFromNotEmpty.isRight()) {
1285 return Either.right(validateDerivedFromNotEmpty.right().value());
1288 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1292 // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
1293 // nodeTypesArtifactsToCreate, true, false, null
1294 private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml,
1295 String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1296 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1297 boolean shouldLock, boolean inTransaction, String nodeName) {
1299 List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
1300 log.trace("************* createResourceFromYaml before parse yaml ");
1301 Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(
1302 yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo,
1304 if (parseResourceInfoFromYamlEither.isRight()) {
1305 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
1306 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1307 return Either.right(responseFormat);
1309 log.trace("************* createResourceFromYaml after parse yaml ");
1310 ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
1311 log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
1312 log.trace("************* createResourceFromYaml before create ");
1313 Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource,
1314 parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
1315 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1316 log.trace("************* createResourceFromYaml after create ");
1317 if (createdResourceResponse.isRight()) {
1318 ResponseFormat responseFormat = createdResourceResponse.right().value();
1319 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
1320 return Either.right(responseFormat);
1323 return createdResourceResponse;
1327 public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName,
1328 Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
1329 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
1330 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
1331 CsarInfo csarInfo) {
1333 Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate,
1334 ToscaTagNamesEnum.TOSCA_VERSION);
1335 if (tosca_version.isRight()) {
1336 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
1337 return Either.right(responseFormat);
1339 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
1340 .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
1341 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
1342 Map<String, Object> mapToConvert = new HashMap<String, Object>();
1343 mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
1344 Resource vfcCreated = null;
1345 if (eitherNodeTypes.isLeft()) {
1346 Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
1347 while (nodesNameValue.hasNext()) {
1348 Entry<String, Object> nodeType = nodesNameValue.next();
1349 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
1350 || nodeTypesArtifactsToHandle.isEmpty() ? null
1351 : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1353 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1354 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1355 Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource,
1356 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1358 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1359 if (handleNeatedVfcYaml.isRight()) {
1360 return Either.right(handleNeatedVfcYaml.right().value());
1362 vfcCreated = handleNeatedVfcYaml.left().value();
1363 } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
1364 && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
1365 log.trace("************* Going to create node {}", nodeType.getKey());
1366 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this
1367 .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
1368 resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
1370 log.debug("************* Finished to create node {}", nodeType.getKey());
1372 if (resourceCreated.isRight()) {
1373 return Either.right(resourceCreated.right().value());
1375 vfcCreated = resourceCreated.left().value().getLeft();
1376 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
1377 vfcCreated.getToscaResourceName());
1379 if (vfcCreated != null) {
1380 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1382 mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
1388 private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource,
1389 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1390 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1393 Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
1394 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1395 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1397 log.debug("************* Going to create node types from yaml {}", yamlName);
1398 Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(
1399 yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1401 if (createNodeTypesRes.isRight()) {
1402 log.debug("Failed to create node types from yaml {}. Status is {}", yamlName,
1403 createNodeTypesRes.right().value());
1404 return Either.right(createNodeTypesRes.right().value());
1406 log.debug("************* Finished to create node types from yaml {}", yamlName);
1408 if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1409 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1410 handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
1411 csarInfo, nodeName, yamlName);
1413 return handleNestedVfcRes;
1416 private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource,
1417 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1418 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1419 String nodeName, String yamlName) {
1421 Either<Resource, ResponseFormat> result = null;
1422 Resource oldComplexVfc = null;
1423 Resource newComplexVfc = null;
1425 Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1426 if (buildCvfcRes.isRight()) {
1427 log.debug("Failed to validate complex VFC for node {}. ", nodeName);
1428 result = buildCvfcRes;
1430 if (result == null) {
1431 newComplexVfc = buildCvfcRes.left().value();
1432 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
1433 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
1434 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
1435 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
1436 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
1437 nodeName).getRight());
1439 if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
1440 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
1441 newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1442 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1443 } else if (oldComplexVfcRes.isLeft()) {
1444 log.debug("validate derived before update");
1445 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
1446 oldComplexVfcRes.left().value(), newComplexVfc,
1447 ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
1448 if (eitherValidation.isLeft()) {
1449 oldComplexVfc = oldComplexVfcRes.left().value();
1453 if (result == null) {
1454 result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
1455 oldComplexVfc, newComplexVfc);
1457 if (result.isLeft()) {
1458 newComplexVfc = result.left().value();
1459 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1460 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
1461 "certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1462 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1463 result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
1465 if (result.isRight()) {
1466 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1469 if (result.isLeft()) {
1470 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1471 csarInfo.getCvfcToCreateQueue().remove();
1476 private Either<Resource, ResponseFormat> handleComplexVfc(
1477 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1478 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
1479 String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1481 Either<Resource, ResponseFormat> handleComplexVfcRes;
1482 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1483 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1484 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
1485 .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
1486 markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1487 if (oldComplexVfc == null) {
1488 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
1489 csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1490 if (handleComplexVfcRes.isRight()) {
1491 log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName);
1494 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
1495 AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
1496 newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
1497 if (handleComplexVfcRes.isRight()) {
1498 log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName);
1501 return handleComplexVfcRes;
1504 private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
1505 Map<String, NodeTypeInfo> nodesInfo) {
1507 Either<Resource, ResponseFormat> result = null;
1508 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1509 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1511 if (!csarInfo.getCvfcToCreateQueue().contains(nodeName)) {
1512 csarInfo.getCvfcToCreateQueue().add(nodeName);
1514 log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(),
1515 csarInfo.getVfResourceName());
1516 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED,
1517 csarInfo.getVfResourceName(), complexVfc.getName()));
1519 if (result == null) {
1520 result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
1521 AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1522 if (result.isRight()) {
1523 log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
1529 private String getNodeTypeActualName(String fullName) {
1530 String nameWithouNamespacePrefix = fullName
1531 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1532 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1533 String resourceType = findTypes[0];
1534 return nameWithouNamespacePrefix.substring(resourceType.length());
1537 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(
1538 String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
1539 Resource resourceVf, boolean needLock,
1540 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1541 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1544 Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf,
1545 nodeNameValue.getKey(), user);
1546 if (resourceMetaData.isRight()) {
1547 return Either.right(resourceMetaData.right().value());
1549 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
1550 resourceMetaData.left().value().getResourceType(), csarInfo);
1552 Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf,
1553 AuditingActionEnum.CHECKIN_RESOURCE, true);
1554 if (eitherCreator.isRight()) {
1555 return Either.right(eitherCreator.right().value());
1557 user = eitherCreator.left().value();
1559 return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock,
1560 nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
1561 nodeNameValue.getKey(), isNested);
1564 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
1565 String nodeResourceType, CsarInfo csarInfo) {
1566 // We need to create a Yaml from each node_types in order to create
1567 // resource from each node type using import normative flow.
1568 DumperOptions options = new DumperOptions();
1569 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1570 Yaml yaml = new Yaml(options);
1572 Map<String, Object> node = new HashMap<>();
1573 node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
1574 .getLeft(), nodeNameValue.getValue());
1575 mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1577 return yaml.dumpAsMap(mapToConvert);
1580 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1582 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator,
1583 resource, AuditingActionEnum.CREATE_RESOURCE);
1584 if (validateDerivedFromNotEmpty.isRight()) {
1585 return Either.right(validateDerivedFromNotEmpty.right().value());
1587 return Either.left(true);
1590 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml,
1591 UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1592 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
1593 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
1594 String nodeName, boolean isNested) {
1596 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import",
1597 LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1598 Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this
1599 .validateResourceCreationFromNodeType(resource, creator);
1600 return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
1601 lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
1602 nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
1605 private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf,
1606 String nodeName, User user) {
1607 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1609 // validate nodetype name prefix
1610 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1611 log.debug("invalid nodeName:{} does not start with {}.", nodeName,
1612 Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1613 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
1614 yamlName, resourceMetaData.getName(), nodeName);
1615 return Either.right(responseFormat);
1618 String actualName = this.getNodeTypeActualName(nodeName);
1619 String namePrefix = nodeName.replace(actualName, "");
1620 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1622 // if we import from csar, the node_type name can be
1623 // org.openecomp.resource.abstract.node_name - in this case we always
1625 if (resourceType.equals(Constants.ABSTRACT)) {
1626 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1629 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1630 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
1631 ResourceTypeEnum.values());
1632 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
1633 yamlName, resourceMetaData.getName(), nodeName);
1634 return Either.right(responseFormat);
1638 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1640 // Setting type from name
1641 String type = resourceType.toUpperCase();
1642 resourceMetaData.setResourceType(type);
1644 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1645 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1646 resourceMetaData.setContactId(user.getUserId());
1647 resourceMetaData.setVendorName(resourceVf.getVendorName());
1648 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1651 List<String> tags = new ArrayList<>();
1652 tags.add(resourceMetaData.getName());
1653 resourceMetaData.setTags(tags);
1656 CategoryDefinition category = new CategoryDefinition();
1657 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1658 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1659 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1660 category.addSubCategory(subCategory);
1661 List<CategoryDefinition> categories = new ArrayList<>();
1662 categories.add(category);
1663 resourceMetaData.setCategories(categories);
1665 return Either.left(resourceMetaData);
1668 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
1669 Map<String, NodeTypeInfo> nodesInfo) {
1670 Resource cvfc = new Resource();
1671 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1672 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1673 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1674 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1675 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1676 cvfc.setAbstract(true);
1677 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1678 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1679 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1680 cvfc.setContactId(csarInfo.getModifier().getUserId());
1681 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1682 cvfc.setVendorName(resourceVf.getVendorName());
1683 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1684 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1685 cvfc.setToscaResourceName(
1686 buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
1688 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1690 List<String> tags = new ArrayList<>();
1691 tags.add(cvfc.getName());
1694 CategoryDefinition category = new CategoryDefinition();
1695 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1696 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1697 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1698 category.addSubCategory(subCategory);
1699 List<CategoryDefinition> categories = new ArrayList<>();
1700 categories.add(category);
1701 cvfc.setCategories(categories);
1703 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1704 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1705 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1710 private String buildCvfcName(String resourceVfName, String nodeName) {
1711 String nameWithouNamespacePrefix = nodeName
1712 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1713 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1714 String resourceType = findTypes[0];
1715 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1716 return addCvfcSuffixToResourceName(resourceName);
1719 private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource,
1720 ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1721 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
1722 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1723 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1724 boolean shouldLock, boolean inTransaction, String nodeName) {
1726 boolean result = true;
1727 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1730 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
1732 if (lockResult.isRight()) {
1733 ResponseFormat responseFormat = lockResult.right().value();
1734 return Either.right(responseFormat);
1736 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1739 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1740 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
1741 if (genericResourceEither.isRight()) {
1743 return genericResourceEither;
1745 Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource,
1746 csarInfo.getModifier(), isNormative, inTransaction);
1747 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1748 if (createResourcesEither.isRight()) {
1750 return createResourcesEither;
1752 resource = createResourcesEither.left().value();
1753 // add groups to resource
1754 log.trace("************* Going to add inputs from yaml {}", yamlName);
1755 if (resource.shouldGenerateInputs())
1756 generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
1758 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1759 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource,
1760 csarInfo.getModifier(), inputs, inTransaction);
1761 if (createInputsOnResource.isRight()) {
1763 return createInputsOnResource;
1765 resource = createInputsOnResource.left().value();
1766 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1768 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
1770 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1772 createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
1773 actionEnum, topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
1774 nodeTypesArtifactsToCreate, nodeName);
1775 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1776 if (createResourcesEither.isRight()) {
1778 return createResourcesEither;
1781 resource = createResourcesEither.left().value();
1782 // validate update vf module group names
1783 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
1784 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1785 if (validateUpdateVfGroupNamesRes.isRight()) {
1787 return Either.right(validateUpdateVfGroupNamesRes.right().value());
1789 // add groups to resource
1790 Map<String, GroupDefinition> groups;
1791 log.trace("************* Going to add groups from yaml {}", yamlName);
1793 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1794 groups = validateUpdateVfGroupNamesRes.left().value();
1796 groups = parsedToscaYamlInfo.getGroups();
1798 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
1799 csarInfo.getModifier(), groups);
1800 if (createGroupsOnResource.isRight()) {
1802 return createGroupsOnResource;
1804 resource = createGroupsOnResource.left().value();
1805 log.trace("************* Finished to add groups from yaml {}", yamlName);
1807 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1809 NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
1810 nodeTypesArtifactsToCreate);
1812 Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
1813 csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
1814 if (createArtifactsEither.isRight()) {
1815 log.debug("failed to update artifacts {}", createArtifactsEither.right().value());
1816 return createArtifactsEither;
1819 resource = createArtifactsEither.left().value();
1821 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1822 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
1823 ASDCKpiApi.countCreatedResourcesKPI();
1824 return Either.left(resource);
1827 if (!inTransaction) {
1829 log.warn("operation failed. do rollback");
1830 titanDao.rollback();
1831 if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
1832 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1833 log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
1837 log.debug("operation success. do commit");
1842 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
1843 NodeTypeEnum.Resource);
1848 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user,
1849 Map<String, GroupDefinition> groups) {
1850 if (groups != null && !groups.isEmpty()) {
1851 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(
1854 if (mergeGroupsUsingResource.isRight()) {
1855 log.debug("Failed to prepare groups for creation");
1856 return Either.right(mergeGroupsUsingResource.right().value());
1858 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1859 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
1861 if (createGroups.isRight()) {
1862 return Either.right(createGroups.right().value());
1865 return Either.left(resource);
1867 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1868 .getToscaElement(resource.getUniqueId());
1869 if (updatedResource.isRight()) {
1870 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1871 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1872 return Either.right(responseFormat);
1874 return Either.left(updatedResource.left().value());
1877 private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user,
1878 Map<String, GroupDefinition> groups) {
1879 if (groups != null && false == groups.isEmpty()) {
1880 List<GroupDefinition> groupsFromResource = resource.getGroups();
1881 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(
1884 if (mergeGroupsUsingResource.isRight()) {
1885 log.debug("Failed to prepare groups for creation");
1886 return Either.right(mergeGroupsUsingResource.right().value());
1888 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1889 List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
1890 List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
1891 List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
1892 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1893 for (GroupDefinition group : groupsAsList) {
1894 Optional<GroupDefinition> op = groupsFromResource.stream()
1895 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1896 if (op.isPresent()) {
1897 GroupDefinition groupToUpdate = op.get();
1898 groupToUpdate.setMembers(group.getMembers());
1899 groupsToUpdate.add(groupToUpdate);
1901 groupsToCreate.add(group);
1904 for (GroupDefinition group : groupsFromResource) {
1905 Optional<GroupDefinition> op = groupsAsList.stream()
1906 .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1907 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1909 groupsToDelete.add(group);
1914 groupsToCreate.addAll(groupsAsList);
1915 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
1916 if (!groupsToCreate.isEmpty()) {
1918 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1919 prepareGroups = groupBusinessLogic.addGroups(resource,
1922 prepareGroups = groupBusinessLogic.createGroups(resource,
1926 if (prepareGroups.isRight()) {
1927 return Either.right(prepareGroups.right().value());
1931 if (!groupsToDelete.isEmpty()) {
1932 prepareGroups = groupBusinessLogic.deleteGroups(resource,
1934 if (prepareGroups.isRight()) {
1935 return Either.right(prepareGroups.right().value());
1939 if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
1940 prepareGroups = groupBusinessLogic.updateGroups(resource, groupsToUpdate);
1941 if (prepareGroups.isRight()) {
1942 return Either.right(prepareGroups.right().value());
1947 return Either.left(resource);
1950 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1951 .getToscaElement(resource.getUniqueId());
1952 if (updatedResource.isRight()) {
1953 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1954 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1955 return Either.right(responseFormat);
1957 return Either.left(updatedResource.left().value());
1960 private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user,
1961 Map<String, InputDefinition> inputs, boolean inTransaction) {
1962 List<InputDefinition> resourceProperties = resource.getInputs();
1963 if ((inputs != null && false == inputs.isEmpty())
1964 || (resourceProperties != null && false == resourceProperties.isEmpty())) {
1966 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
1968 if (createInputs.isRight()) {
1969 return Either.right(createInputs.right().value());
1972 return Either.left(resource);
1975 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
1976 .getToscaElement(resource.getUniqueId());
1977 if (updatedResource.isRight()) {
1978 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
1979 componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1980 return Either.right(responseFormat);
1982 return Either.left(updatedResource.left().value());
1985 private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(
1986 Map<String, GroupDefinition> groups, Resource component) {
1988 List<GroupDefinition> result = new ArrayList<>();
1990 List<ComponentInstance> componentInstances = component.getComponentInstances();
1992 if (groups != null) {
1993 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1994 if (validateCyclicGroupsDependencies.isRight()) {
1995 return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
1997 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1998 String groupName = entry.getKey();
2000 GroupDefinition groupDefinition = entry.getValue();
2002 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
2003 updatedGroupDefinition.setMembers(null);
2005 // get the members of the group
2006 Map<String, String> members = groupDefinition.getMembers();
2007 if (members != null) {
2008 Set<String> compInstancesNames = members.keySet();
2010 if (componentInstances == null || true == componentInstances.isEmpty()) {
2011 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
2013 "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
2014 membersAstString, groupName, component.getNormalizedName());
2015 return Either.right(componentsUtils.getResponseFormat(
2016 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
2017 component.getNormalizedName(), getComponentTypeForResponse(component)));
2019 // Find all component instances with the member names
2020 Map<String, String> memberNames = componentInstances.stream()
2021 .collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
2022 memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
2023 Map<String, String> relevantInstances = memberNames.entrySet().stream()
2024 .filter(n -> compInstancesNames.contains(n.getKey()))
2025 .collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
2027 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
2029 List<String> foundMembers = new ArrayList<>();
2030 if (relevantInstances != null) {
2031 foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
2033 compInstancesNames.removeAll(foundMembers);
2034 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
2035 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
2036 groupName, component.getNormalizedName());
2037 return Either.right(componentsUtils.getResponseFormat(
2038 ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
2039 component.getNormalizedName(), getComponentTypeForResponse(component)));
2042 updatedGroupDefinition.setMembers(relevantInstances);
2045 result.add(updatedGroupDefinition);
2048 return Either.left(result);
2052 * This Method validates that there is no cyclic group dependencies. meaning
2053 * group A as member in group B which is member in group A
2058 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
2060 Either<Boolean, ResponseFormat> result = Either.left(true);
2062 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
2063 while (allGroupsItr.hasNext() && result.isLeft()) {
2064 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
2065 // Fetches a group member A
2066 String groupAName = groupAEntry.getKey();
2067 // Finds all group members in group A
2068 Set<String> allGroupAMembersNames = new HashSet<>();
2069 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
2070 // If A is a group member of itself found cyclic dependency
2071 if (allGroupAMembersNames.contains(groupAName)) {
2072 ResponseFormat responseFormat = componentsUtils
2073 .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
2074 result = Either.right(responseFormat);
2077 } catch (Exception e) {
2078 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2079 result = Either.right(responseFormat);
2080 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
2086 * This Method fills recursively the set groupMembers with all the members
2087 * of the given group which are also of type group.
2091 * @param allGroupMembers
2094 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
2095 Set<String> allGroupMembers) {
2097 // Found Cyclic dependency
2098 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
2101 GroupDefinition groupDefinition = allGroups.get(groupName);
2102 // All Members Of Current Group Resource Instances & Other Groups
2103 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
2104 // Filtered Members Of Current Group containing only members which
2106 List<String> currGroupFilteredMembers = currGroupMembers.stream().
2107 // Keep Only Elements of type group and not Resource Instances
2108 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
2109 // Add Filtered Elements to main Set
2110 peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
2112 collect(Collectors.toList());
2114 // Recursively call the method for all the filtered group members
2115 for (String innerGroupName : currGroupFilteredMembers) {
2116 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
2121 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
2122 Set<String> allGroupMembers) {
2124 boolean stop = false;
2125 // In Case Not Group Stop
2126 if (!allGroups.containsKey(groupName)) {
2129 // In Case Group Has no members stop
2131 GroupDefinition groupDefinition = allGroups.get(groupName);
2132 stop = MapUtils.isEmpty(groupDefinition.getMembers());
2135 // In Case all group members already contained stop
2137 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
2138 Set<String> membersOfTypeGroup = allMembers.stream().
2139 // Filter In Only Group members
2140 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
2142 collect(Collectors.toSet());
2143 stop = allGroupMembers.containsAll(membersOfTypeGroup);
2148 private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource,
2149 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
2150 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
2151 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
2152 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
2155 Either<Resource, ResponseFormat> result;
2156 Either<Resource, ResponseFormat> createResourcesInstancesEither;
2158 log.debug("************* Going to create all nodes {}", yamlName);
2159 Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName,
2160 resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
2161 nodeTypesInfo, csarInfo, nodeName);
2162 log.debug("************* Finished to create all nodes {}", yamlName);
2163 if (createdResourcesFromdNodeTypeMap.isRight()) {
2164 log.debug("failed to resources from node types status is {}",
2165 createdResourcesFromdNodeTypeMap.right().value());
2166 return Either.right(createdResourcesFromdNodeTypeMap.right().value());
2169 log.debug("************* Going to create all resource instances {}", yamlName);
2170 createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource,
2171 uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes());
2173 log.debug("************* Finished to create all resource instances {}", yamlName);
2174 if (createResourcesInstancesEither.isRight()) {
2175 log.debug("failed to create resource instances status is {}",
2176 createResourcesInstancesEither.right().value());
2177 result = createResourcesInstancesEither;
2178 return createResourcesInstancesEither;
2180 resource = createResourcesInstancesEither.left().value();
2181 log.debug("************* Going to create all relations {}", yamlName);
2182 createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource,
2183 uploadComponentInstanceInfoMap);
2185 log.debug("************* Finished to create all relations {}", yamlName);
2187 if (createResourcesInstancesEither.isRight()) {
2188 log.debug("failed to create relation between resource instances status is {}",
2189 createResourcesInstancesEither.right().value());
2190 result = createResourcesInstancesEither;
2193 resource = createResourcesInstancesEither.left().value();
2196 log.debug("************* Going to create positions {}", yamlName);
2197 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic
2198 .setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
2199 log.debug("************* Finished to set positions {}", yamlName);
2200 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
2205 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
2206 List<ArtifactDefinition> artifactsToAdd) {
2207 List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName())
2208 .collect(Collectors.toList());
2209 artifactsToAdd.stream().forEach(a -> {
2210 if (!vfcArtifactNames.contains(a.getArtifactName())) {
2211 vfcArtifacts.add(a);
2213 log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
2219 @SuppressWarnings("unchecked")
2220 private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource,
2221 String topologyTemplateYaml, boolean needLock,
2222 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
2223 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
2224 CsarInfo csarInfo, String nodeName) {
2226 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
2227 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
2228 if (nodeTypeEntry.getValue().isNested()) {
2230 Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource,
2231 nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
2232 nodeTypeEntry.getKey());
2233 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
2234 if (createResourceFromYaml.isRight()) {
2235 return Either.right(createResourceFromYaml.right().value());
2240 Map<String, Object> mappedToscaTemplate = null;
2241 if (StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
2242 && nodeTypesInfo.containsKey(nodeName)) {
2243 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
2245 if (MapUtils.isEmpty(mappedToscaTemplate)) {
2246 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
2249 Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(
2250 yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
2251 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
2252 if (createdNodeTypeFromMainTemplateEither.isRight()) {
2253 ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
2254 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
2255 return Either.right(responseFormat);
2258 // add the created node types to the cache although they are not in the
2260 csarInfo.getCreatedNodes().values().stream()
2261 .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
2266 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
2267 List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
2268 boolean inTransaction) {
2270 if (csarInfo.getCsar() != null) {
2271 String vendorLicenseModelId = null;
2272 String vfLicenseModelId = null;
2274 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
2275 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
2276 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
2277 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
2278 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
2279 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
2280 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
2281 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
2286 // Specific Behavior for license artifacts
2287 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2288 CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
2289 ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
2290 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
2291 Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, false, shouldLock,
2293 createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
2294 CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
2295 ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
2296 Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
2297 artifactOperation, null, false, shouldLock, inTransaction);
2299 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
2300 createdArtifacts, shouldLock, inTransaction, artifactOperation);
2301 if (eitherCreateResult.isRight()) {
2302 return Either.right(eitherCreateResult.right().value());
2304 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
2305 .getToscaElement(resource.getUniqueId());
2306 if (eitherGerResource.isRight()) {
2307 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2308 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2310 return Either.right(responseFormat);
2313 resource = eitherGerResource.left().value();
2315 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
2317 if (artifacsMetaCsarStatus.isLeft()) {
2318 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
2319 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
2320 Either<Resource, ResponseFormat> createArtifactsFromCsar;
2321 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum()))
2322 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2324 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2326 if (createArtifactsFromCsar.isRight()) {
2327 log.debug("Couldn't create artifacts from artifacts.meta");
2328 return Either.right(createArtifactsFromCsar.right().value());
2331 return Either.left(createArtifactsFromCsar.left().value());
2334 return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
2338 return Either.left(resource);
2342 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
2343 String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
2344 String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
2345 ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
2346 boolean inTransaction) {
2347 byte[] artifactFileBytes = null;
2349 if (csarInfo.getCsar().containsKey(artifactPath)) {
2350 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
2352 Either<Boolean, ResponseFormat> result = Either.left(true);
2353 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
2354 if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
2355 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
2356 shouldLock, inTransaction);
2357 if (handleDelete.isRight()) {
2358 result = Either.right(handleDelete.right().value());
2364 if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
2365 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2366 ArtifactOperationEnum.CREATE);
2370 if (artifactFileBytes != null) {
2371 Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
2372 artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
2373 artifactFileBytes, null, isFromCsar);
2374 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
2375 resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
2376 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2377 if (eitherNonMetaArtifacts.isRight()) {
2378 BeEcompErrorManager.getInstance()
2379 .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
2380 + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
2381 ErrorSeverity.WARNING);
2382 return Either.right(eitherNonMetaArtifacts.right().value());
2388 private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
2389 return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
2393 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
2394 List<ArtifactDefinition> createdArtifacts,
2395 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2396 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
2397 && eitherNonMetaArtifacts.isLeft()) {
2398 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
2399 if (eitherResult.isLeft()) {
2400 createdArtifacts.add(eitherResult.left().value());
2406 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
2407 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2408 ArtifactOperationInfo artifactOperation) {
2410 Either<Resource, ResponseFormat> resStatus = null;
2411 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2414 List<NonMetaArtifactInfo> artifactPathAndNameList =
2415 // Stream of file paths contained in csar
2416 csarInfo.getCsar().entrySet().stream()
2417 // Filter in only VF artifact path location
2418 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
2420 // Validate and add warnings
2421 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
2422 collectedWarningMessages))
2423 // Filter in Non Warnings
2424 .filter(e -> e.isLeft())
2425 // Convert from Either to NonMetaArtifactInfo
2426 .map(e -> e.left().value())
2428 .collect(Collectors.toList());
2430 Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
2431 if (responseFormatEither.isRight()) {
2432 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
2433 ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
2436 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2438 if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
2439 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2440 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
2442 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
2443 resource, artifactPathAndNameList, csarInfo.getModifier());
2445 if (findVfCsarArtifactsToHandleRes.isRight()) {
2446 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2448 if (resStatus == null) {
2449 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2454 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2456 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
2459 Optional<ResponseFormat> optionalCreateInDBError =
2460 // Stream of artifacts to be created
2461 currArtifactOperationPair.getValue().stream()
2462 // create each artifact
2463 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
2464 e.getArtifactName(), e.getArtifactType().getType(),
2465 e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2466 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
2467 artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
2468 currArtifactOperationPair.getKey()),
2469 createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
2470 // filter in only error
2471 .filter(e -> e.isRight()).
2472 // Convert the error from either to
2474 map(e -> e.right().value()).
2475 // Check if an error occurred
2477 // Error found on artifact Creation
2478 if (optionalCreateInDBError.isPresent()) {
2479 resStatus = Either.right(optionalCreateInDBError.get());
2484 if (resStatus == null) {
2485 resStatus = Either.left(resource);
2487 } catch (Exception e) {
2488 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2489 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2491 CsarUtils.handleWarningMessages(collectedWarningMessages);
2496 private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
2497 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2498 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2499 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2500 return Either.right(nonMetaArtifactInfo.getArtifactName());
2503 return Either.left(true);
2506 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
2507 Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2509 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2510 // collect all Deployment and Informational artifacts of VF
2511 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2512 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2514 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2515 existingArtifacts.addAll(resource.getArtifacts().values());
2517 existingArtifacts = existingArtifacts.stream()
2518 // filter MANDATORY artifacts, LICENSE artifacts and artifacts
2519 // was created from HEAT.meta
2520 .filter(this::isNonMetaArtifact).collect(Collectors.toList());
2522 List<String> artifactsToIgnore = new ArrayList<>();
2523 // collect IDs of Artifacts of VF which belongs to any group
2524 if (resource.getGroups() != null) {
2525 resource.getGroups().stream().forEach(g -> {
2526 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
2527 artifactsToIgnore.addAll(g.getArtifacts());
2530 existingArtifacts = existingArtifacts.stream()
2531 // filter artifacts which belongs to any group
2532 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
2533 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2536 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2537 boolean result = true;
2538 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2544 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2545 boolean result = true;
2546 if (artifact.getArtifactType() == null
2547 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
2548 || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2554 private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName,
2555 Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2556 log.debug("createResourceInstancesRelations try to create relations ");
2557 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2558 if (uploadResInstancesMap == null) {
2559 log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
2560 BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}",
2561 yamlName, ErrorSeverity.ERROR);
2563 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2565 return Either.right(responseFormat);
2568 if (componentInstancesList == null || componentInstancesList.isEmpty()) {
2569 log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
2570 BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ",
2571 resource.getUniqueId(), ErrorSeverity.ERROR);
2573 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2575 return Either.right(responseFormat);
2578 log.debug("Before validateAndUpdatePropertyValue");
2579 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
2580 if (allDataTypes.isRight()) {
2581 TitanOperationStatus status = allDataTypes.right().value();
2582 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
2583 "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2584 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2585 DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
2589 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
2590 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
2591 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
2592 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
2593 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
2594 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
2595 Map<String, Resource> originCompMap = new HashMap<>();
2596 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
2598 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
2600 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2601 log.trace("Processing entry: {}", entry);
2602 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2603 ComponentInstance currentCompInstance = null;
2604 for (ComponentInstance compInstance : componentInstancesList) {
2605 log.trace("Processing component instance: {}", compInstance);
2606 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2607 currentCompInstance = compInstance;
2612 if (currentCompInstance == null) {
2613 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
2614 resource.getUniqueId());
2615 BeEcompErrorManager.getInstance().logInternalDataError(
2616 "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
2617 resource.getUniqueId(), ErrorSeverity.ERROR);
2618 ResponseFormat responseFormat = componentsUtils
2619 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2620 return Either.right(responseFormat);
2622 String resourceInstanceId = currentCompInstance.getUniqueId();
2623 Resource originResource;
2624 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
2625 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
2626 .getToscaFullElement(currentCompInstance.getComponentUid());
2627 if (getOriginResourceRes.isRight()) {
2628 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
2629 currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
2630 getOriginResourceRes);
2631 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2632 componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
2633 return Either.right(responseFormat);
2635 originResource = getOriginResourceRes.left().value();
2636 originCompMap.put(originResource.getUniqueId(), originResource);
2638 originResource = originCompMap.get(currentCompInstance.getComponentUid());
2640 if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
2641 instRequirements.put(currentCompInstance, originResource.getRequirements());
2642 if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
2643 Map<String, List<CapabilityDefinition>> originCapabilities;
2644 if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
2645 originCapabilities = new HashMap<>();
2646 originResource.getCapabilities().entrySet().stream().forEach(e -> {
2647 List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l))
2648 .collect(Collectors.toList());
2649 originCapabilities.put(e.getKey(), list);
2651 Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
2652 for (List<UploadCapInfo> capabilities : uploadComponentInstanceInfo.getCapabilities().values()) {
2653 for (UploadCapInfo capability : capabilities) {
2654 if (CollectionUtils.isNotEmpty(capability.getProperties())) {
2655 newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
2656 .collect(Collectors.toMap(p -> p.getName(), p -> p)));
2660 for (List<CapabilityDefinition> capabilities : originCapabilities.values()) {
2661 List<CapabilityDefinition> filteredCapabilities = capabilities.stream()
2662 .filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList());
2663 for (CapabilityDefinition cap : filteredCapabilities) {
2664 Either<Boolean, ResponseFormat> updateRes = updatePropertyValues(cap.getProperties(),
2665 newPropertiesMap.get(cap.getName()), allDataTypes.left().value());
2666 if (updateRes.isRight()) {
2667 log.debug("Failed to update capability properties of capability {} . Status is {}. ",
2668 cap.getName(), updateRes.right().value());
2669 return Either.right(updateRes.right().value());
2674 originCapabilities = originResource.getCapabilities();
2676 instCapabilties.put(currentCompInstance, originCapabilities);
2678 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
2679 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
2680 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
2681 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
2682 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
2683 instAttributes.put(resourceInstanceId, originResource.getAttributes());
2684 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
2685 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
2686 originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
2687 if (addPropertiesValueToRiRes.getStatus() != 200) {
2688 return Either.right(addPropertiesValueToRiRes);
2691 ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource,
2692 originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
2693 if (addInputValueToRiRes.getStatus() != 200) {
2694 return Either.right(addInputValueToRiRes);
2699 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
2700 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
2701 if (addPropToInst.isRight()) {
2702 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
2703 addPropToInst.right().value());
2704 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2705 componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
2706 return Either.right(responseFormat);
2708 if (instInputs != null && !instInputs.isEmpty()) {
2709 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
2710 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
2711 if (addInputToInst.isRight()) {
2712 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
2713 addInputToInst.right().value());
2714 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
2715 componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
2716 return Either.right(responseFormat);
2719 StorageOperationStatus addArtToInst = toscaOperationFacade
2720 .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
2721 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2722 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2723 ResponseFormat responseFormat = componentsUtils
2724 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2725 return Either.right(responseFormat);
2728 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user);
2729 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2730 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
2731 ResponseFormat responseFormat = componentsUtils
2732 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2733 return Either.right(responseFormat);
2736 addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements,
2737 resource.getUniqueId());
2738 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2739 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
2741 ResponseFormat responseFormat = componentsUtils
2742 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2743 return Either.right(responseFormat);
2746 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
2747 resource.getUniqueId());
2748 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2749 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
2751 ResponseFormat responseFormat = componentsUtils
2752 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2753 return Either.right(responseFormat);
2756 ComponentParametersView parametersView = new ComponentParametersView();
2757 parametersView.disableAll();
2758 parametersView.setIgnoreComponentInstances(false);
2759 parametersView.setIgnoreComponentInstancesProperties(false);
2760 parametersView.setIgnoreCapabilities(false);
2761 parametersView.setIgnoreRequirements(false);
2763 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
2764 .getToscaElement(resource.getUniqueId(), parametersView);
2766 if (eitherGetResource.isRight()) {
2767 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2768 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2770 return Either.right(responseFormat);
2774 resource = eitherGetResource.left().value();
2776 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
2777 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
2778 ComponentInstance currentCompInstance = null;
2779 for (ComponentInstance compInstance : componentInstancesList) {
2781 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2782 currentCompInstance = compInstance;
2787 if (currentCompInstance == null) {
2788 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
2789 resource.getUniqueId());
2790 BeEcompErrorManager.getInstance().logInternalDataError(
2791 "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
2792 resource.getUniqueId(), ErrorSeverity.ERROR);
2793 ResponseFormat responseFormat = componentsUtils
2794 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
2795 return Either.right(responseFormat);
2798 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
2799 if (addRelationToRiRes.getStatus() != 200) {
2800 return Either.right(addRelationToRiRes);
2804 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
2805 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
2806 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
2808 ResponseFormat responseFormat = componentsUtils
2809 .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
2810 return Either.right(responseFormat);
2813 if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
2814 eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
2815 if (eitherGetResource.isRight()) {
2816 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2817 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2818 return Either.right(responseFormat);
2820 eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(),
2821 uploadResInstancesMap);
2822 if (eitherGetResource.isRight()) {
2823 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2824 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2825 return Either.right(responseFormat);
2829 log.debug("************* in create relations, getResource start");
2830 eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2831 log.debug("************* in create relations, getResource end");
2832 if (eitherGetResource.isRight()) {
2833 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
2834 componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2835 return Either.right(responseFormat);
2837 return Either.left(eitherGetResource.left().value());
2840 private Either<Boolean, ResponseFormat> updatePropertyValues(List<ComponentInstanceProperty> properties,
2841 Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
2842 for (ComponentInstanceProperty property : properties) {
2843 Either<String, StorageOperationStatus> updateRes = updatePropertyValue(property,
2844 newProperties.get(property.getName()), allDataTypes);
2845 if (updateRes.isRight()) {
2846 log.debug("Failed to update capability property {} . Status is {}. ", property.getName(),
2847 updateRes.right().value());
2848 return Either.right(componentsUtils
2849 .getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value())));
2852 return Either.left(true);
2855 private Either<String, StorageOperationStatus> updatePropertyValue(ComponentInstanceProperty property,
2856 UploadPropInfo propertyInfo, Map<String, DataTypeDefinition> allDataTypes) {
2857 String value = null;
2858 List<GetInputValueDataDefinition> getInputs = null;
2859 boolean isValidate = true;
2860 if (propertyInfo.getValue() != null) {
2861 getInputs = propertyInfo.getGet_input();
2862 isValidate = getInputs == null || getInputs.isEmpty();
2864 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
2866 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
2867 ToscaTagNamesEnum.GET_INPUT.getElementName());
2869 property.setValue(value);
2870 return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
2873 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
2874 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
2875 Either<Resource, StorageOperationStatus> updateRes = null;
2876 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
2877 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
2878 StorageOperationStatus status = toscaOperationFacade
2879 .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
2880 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2882 "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
2883 resource.getUniqueId(), status);
2884 updateRes = Either.right(status);
2886 if (updateRes == null) {
2887 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
2888 updatedInstCapabilities, updatedInstRequirements);
2889 status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
2890 resource.getUniqueId());
2891 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
2893 "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
2894 resource.getUniqueId(), status);
2895 updateRes = Either.right(status);
2898 if (updateRes == null) {
2899 updateRes = Either.left(resource);
2904 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
2905 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
2906 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
2907 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
2909 componentInstances.stream().forEach(i -> {
2910 fillUpdatedInstCapabilities(updatedInstCapabilities, i,
2911 uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
2912 fillUpdatedInstRequirements(updatedInstRequirements, i,
2913 uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
2917 private void fillUpdatedInstRequirements(
2918 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
2919 ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
2920 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
2921 Set<String> updatedReqNames = new HashSet<>();
2922 if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
2923 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
2924 updatedRequirements.put(requirements.getKey(),
2925 requirements.getValue().stream()
2926 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
2927 && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
2929 r.setParentName(r.getName());
2930 r.setName(requirementsNamesToUpdate.get(r.getName()));
2931 updatedReqNames.add(r.getName());
2933 }).collect(Collectors.toList()));
2936 if (MapUtils.isNotEmpty(updatedRequirements)) {
2937 updatedInstRequirements.put(instance, updatedRequirements);
2941 private void fillUpdatedInstCapabilities(
2942 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
2943 ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
2944 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
2945 Set<String> updatedCapNames = new HashSet<>();
2946 if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
2947 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
2948 updatedCapabilities.put(requirements.getKey(),
2949 requirements.getValue().stream()
2950 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
2951 && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
2953 c.setParentName(c.getName());
2954 c.setName(capabilitiesNamesToUpdate.get(c.getName()));
2955 updatedCapNames.add(c.getName());
2957 }).collect(Collectors.toList()));
2960 if (MapUtils.isNotEmpty(updatedCapabilities)) {
2961 updatedInstCapabilties.put(instance, updatedCapabilities);
2965 private ResponseFormat addRelationToRI(String yamlName, Resource resource,
2966 UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
2967 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
2969 UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
2971 ComponentInstance currentCompInstance = null;
2973 for (ComponentInstance compInstance : componentInstancesList) {
2975 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
2976 currentCompInstance = compInstance;
2982 if (currentCompInstance == null) {
2983 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
2984 resource.getUniqueId());
2985 BeEcompErrorManager.getInstance().logInternalDataError(
2986 "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
2987 resource.getUniqueId(), ErrorSeverity.ERROR);
2988 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
2990 return responseFormat;
2992 String resourceInstanceId = currentCompInstance.getUniqueId();
2994 Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
2996 if (regMap != null) {
2997 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
2999 while (nodesRegValue.hasNext()) {
3000 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3002 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3003 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3004 log.debug("Going to create relation {}", uploadRegInfo.getName());
3005 String regName = uploadRegInfo.getName();
3006 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3007 regCapRelDef.setFromNode(resourceInstanceId);
3008 log.debug("try to find available requirement {} ", regName);
3009 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
3010 yamlName, uploadComponentInstanceInfo, currentCompInstance,
3011 uploadRegInfo.getCapabilityName());
3012 if (eitherReqStatus.isRight()) {
3013 log.debug("failed to find available requirement {} status is {}", regName,
3014 eitherReqStatus.right().value());
3015 return eitherReqStatus.right().value();
3018 RequirementDefinition validReq = eitherReqStatus.left().value();
3019 List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
3020 .getRelationships();
3021 if (reqAndRelationshipPairList == null)
3022 reqAndRelationshipPairList = new ArrayList<>();
3023 RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
3024 reqAndRelationshipPair.setRequirement(regName);
3025 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3026 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3027 RelationshipImpl relationship = new RelationshipImpl();
3028 relationship.setType(validReq.getCapability());
3029 reqAndRelationshipPair.setRelationships(relationship);
3031 ComponentInstance currentCapCompInstance = null;
3032 for (ComponentInstance compInstance : componentInstancesList) {
3033 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
3034 currentCapCompInstance = compInstance;
3039 if (currentCapCompInstance == null) {
3040 log.debug("The component instance with name {} not found on resource {} ",
3041 uploadRegInfo.getNode(), resource.getUniqueId());
3042 BeEcompErrorManager.getInstance().logInternalDataError(
3043 "component instance with name " + uploadRegInfo.getNode() + " in resource {} ",
3044 resource.getUniqueId(), ErrorSeverity.ERROR);
3045 ResponseFormat responseFormat = componentsUtils
3046 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3047 return responseFormat;
3049 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3050 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3051 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
3052 currentCapCompInstance, uploadRegInfo);
3053 if (aviableCapForRel == null) {
3054 log.debug("aviable capability was not found. req name is {} component instance is {}",
3055 validReq.getName(), currentCapCompInstance.getUniqueId());
3056 BeEcompErrorManager.getInstance().logInternalDataError(
3057 "aviable capability was not found. req name is " + validReq.getName()
3058 + " component instance is " + currentCapCompInstance.getUniqueId(),
3059 resource.getUniqueId(), ErrorSeverity.ERROR);
3060 ResponseFormat responseFormat = componentsUtils
3061 .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3062 return responseFormat;
3064 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3065 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3066 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3067 CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
3068 capReqRel.setRelation(reqAndRelationshipPair);
3069 reqAndRelationshipPairList.add(capReqRel);
3070 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3071 relations.add(regCapRelDef);
3074 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3075 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3076 return responseFormat;
3078 return componentsUtils.getResponseFormat(ActionStatus.OK);
3081 private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3082 Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3083 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3084 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3085 if (propMap != null && propMap.size() > 0) {
3086 Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
3088 List<InputDefinition> listFromMap = originResource.getInputs();
3089 if (listFromMap == null || listFromMap.isEmpty()) {
3090 log.debug("failed to find properties ");
3091 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3092 return responseFormat;
3094 for (InputDefinition prop : listFromMap) {
3095 String propName = prop.getName();
3096 if (!currPropertiesMap.containsKey(propName)) {
3097 currPropertiesMap.put(propName, prop);
3100 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3101 for (List<UploadPropInfo> propertyList : propMap.values()) {
3103 UploadPropInfo propertyInfo = propertyList.get(0);
3104 String propName = propertyInfo.getName();
3105 if (!currPropertiesMap.containsKey(propName)) {
3106 log.debug("failed to find property {} ", propName);
3107 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
3109 return responseFormat;
3111 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3112 ComponentInstanceInput property = null;
3114 String value = null;
3115 List<GetInputValueDataDefinition> getInputs = null;
3116 boolean isValidate = true;
3117 if (propertyInfo.getValue() != null) {
3118 getInputs = propertyInfo.getGet_input();
3119 isValidate = getInputs == null || getInputs.isEmpty();
3121 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
3122 curPropertyDef.getType());
3124 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
3125 ToscaTagNamesEnum.GET_INPUT.getElementName());
3127 String innerType = null;
3128 property = new ComponentInstanceInput(curPropertyDef, value, null);
3130 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property,
3131 value, isValidate, innerType, allDataTypes);
3132 if (validatevalueEiter.isRight()) {
3133 return componentsUtils.getResponseFormat(
3134 componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3137 property.setValue(validatevalueEiter.left().value());
3139 if (getInputs != null && !getInputs.isEmpty()) {
3140 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3141 for (GetInputValueDataDefinition getInput : getInputs) {
3142 List<InputDefinition> inputs = resource.getInputs();
3143 if (inputs == null || inputs.isEmpty()) {
3144 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
3145 property, currentCompInstance.getUniqueId());
3146 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3149 Optional<InputDefinition> optional = inputs.stream()
3150 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3151 if (!optional.isPresent()) {
3152 log.debug("Failed to find input {} ", getInput.getInputName());
3153 // @@TODO error message
3154 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3156 InputDefinition input = optional.get();
3157 getInput.setInputId(input.getUniqueId());
3158 getInputValues.add(getInput);
3160 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3161 if (getInputIndex != null) {
3162 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
3164 if (!optional.isPresent()) {
3165 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3166 // @@TODO error message
3167 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3169 InputDefinition inputIndex = optional.get();
3170 getInputIndex.setInputId(inputIndex.getUniqueId());
3171 getInputValues.add(getInputIndex);
3174 property.setGetInputValues(getInputValues);
3176 instPropList.add(property);
3177 // delete overriden property
3178 currPropertiesMap.remove(property.getName());
3180 // add rest of properties
3181 if (!currPropertiesMap.isEmpty()) {
3182 for (InputDefinition value : currPropertiesMap.values()) {
3183 instPropList.add(new ComponentInstanceInput(value));
3186 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
3188 return componentsUtils.getResponseFormat(ActionStatus.OK);
3191 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
3192 Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3193 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3195 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3196 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
3198 List<PropertyDefinition> listFromMap = originResource.getProperties();
3199 if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
3200 log.debug("failed to find properties ");
3201 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3202 return responseFormat;
3204 if (listFromMap == null || listFromMap.isEmpty()) {
3205 return componentsUtils.getResponseFormat(ActionStatus.OK);
3207 for (PropertyDefinition prop : listFromMap) {
3208 String propName = prop.getName();
3209 if (!currPropertiesMap.containsKey(propName)) {
3210 currPropertiesMap.put(propName, prop);
3213 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3214 if (propMap != null && propMap.size() > 0) {
3215 for (List<UploadPropInfo> propertyList : propMap.values()) {
3217 UploadPropInfo propertyInfo = propertyList.get(0);
3218 String propName = propertyInfo.getName();
3219 if (!currPropertiesMap.containsKey(propName)) {
3220 log.debug("failed to find property {} ", propName);
3221 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
3223 return responseFormat;
3225 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3226 ComponentInstanceProperty property = null;
3228 String value = null;
3229 List<GetInputValueDataDefinition> getInputs = null;
3230 boolean isValidate = true;
3231 if (propertyInfo.getValue() != null) {
3232 getInputs = propertyInfo.getGet_input();
3233 isValidate = getInputs == null || getInputs.isEmpty();
3235 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
3236 curPropertyDef.getType());
3238 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
3239 ToscaTagNamesEnum.GET_INPUT.getElementName());
3241 String innerType = null;
3242 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3244 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property,
3245 value, isValidate, innerType, allDataTypes);
3246 if (validatevalueEiter.isRight()) {
3247 return componentsUtils.getResponseFormat(
3248 componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3251 property.setValue(validatevalueEiter.left().value());
3253 if (getInputs != null && !getInputs.isEmpty()) {
3254 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3255 for (GetInputValueDataDefinition getInput : getInputs) {
3256 List<InputDefinition> inputs = resource.getInputs();
3257 if (inputs == null || inputs.isEmpty()) {
3258 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
3259 property, currentCompInstance.getUniqueId());
3260 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3263 Optional<InputDefinition> optional = inputs.stream()
3264 .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3265 if (!optional.isPresent()) {
3266 log.debug("Failed to find input {} ", getInput.getInputName());
3267 // @@TODO error message
3268 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3270 InputDefinition input = optional.get();
3271 getInput.setInputId(input.getUniqueId());
3272 getInputValues.add(getInput);
3274 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3275 if (getInputIndex != null) {
3276 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
3278 if (!optional.isPresent()) {
3279 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3280 // @@TODO error message
3281 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3283 InputDefinition inputIndex = optional.get();
3284 getInputIndex.setInputId(inputIndex.getUniqueId());
3285 getInputValues.add(getInputIndex);
3290 property.setGetInputValues(getInputValues);
3292 instPropList.add(property);
3293 // delete overriden property
3294 currPropertiesMap.remove(property.getName());
3297 // add rest of properties
3298 if (!currPropertiesMap.isEmpty()) {
3299 for (PropertyDefinition value : currPropertiesMap.values()) {
3300 instPropList.add(new ComponentInstanceProperty(value));
3303 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3304 return componentsUtils.getResponseFormat(ActionStatus.OK);
3307 // US740820 Relate RIs according to capability name
3308 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
3309 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3310 if (null == uploadReqInfo.getCapabilityName()
3311 || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
3315 return findAviableCapability(validReq, currentCapCompInstance);
3317 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3320 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
3321 ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3322 CapabilityDefinition cap = null;
3323 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3324 if (!capMap.containsKey(validReq.getCapability())) {
3327 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
3328 .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
3329 if (!capByName.isPresent()) {
3332 cap = capByName.get();
3334 if (cap.getMaxOccurrences() != null
3335 && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
3336 String leftOccurrences = cap.getLeftOccurrences();
3337 int left = Integer.parseInt(leftOccurrences);
3340 cap.setLeftOccurrences(String.valueOf(left));
3348 private CapabilityDefinition findAviableCapability(RequirementDefinition validReq,
3349 ComponentInstance currentCapCompInstance) {
3350 CapabilityDefinition aviableCapForRel = null;
3351 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3352 if (capMap.containsKey(validReq.getCapability())) {
3353 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3355 for (CapabilityDefinition cap : capList) {
3356 if (cap.getMaxOccurrences() != null
3357 && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
3358 String leftOccurrences = cap.getLeftOccurrences();
3359 if (leftOccurrences == null) {
3360 leftOccurrences = cap.getMaxOccurrences();
3362 int left = Integer.parseInt(leftOccurrences);
3365 cap.setLeftOccurrences(String.valueOf(left));
3366 aviableCapForRel = cap;
3372 aviableCapForRel = cap;
3377 return aviableCapForRel;
3380 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
3381 UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
3383 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3384 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3385 RequirementDefinition validRegDef = null;
3387 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3388 for (RequirementDefinition reqDef : entry.getValue()) {
3389 if (reqDef.getName().equals(regName)) {
3390 if (reqDef.getMaxOccurrences() != null
3391 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3392 String leftOccurrences = reqDef.getLeftOccurrences();
3393 if (leftOccurrences == null) {
3394 leftOccurrences = reqDef.getMaxOccurrences();
3396 int left = Integer.parseInt(leftOccurrences);
3399 reqDef.setLeftOccurrences(String.valueOf(left));
3400 validRegDef = reqDef;
3406 validRegDef = reqDef;
3412 if (validRegDef != null) {
3417 for (RequirementDefinition reqDef : list) {
3418 if (reqDef.getName().equals(regName)) {
3419 if (reqDef.getMaxOccurrences() != null
3420 && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3421 String leftOccurrences = reqDef.getLeftOccurrences();
3422 if (leftOccurrences == null) {
3423 leftOccurrences = reqDef.getMaxOccurrences();
3425 int left = Integer.parseInt(leftOccurrences);
3428 reqDef.setLeftOccurrences(String.valueOf(left));
3429 validRegDef = reqDef;
3435 validRegDef = reqDef;
3441 if (validRegDef == null) {
3442 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3443 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3444 return Either.right(responseFormat);
3446 return Either.left(validRegDef);
3449 @SuppressWarnings("unchecked")
3450 public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource,
3451 String resourceYml, Map<String, String> createdNodesToscaResourceNames,
3452 Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
3454 Map<String, Object> mappedToscaTemplate;
3455 if (nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)) {
3456 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
3459 // DE154502 Fail if duplicate key found in file
3460 mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
3462 } catch (ParserException e) {
3463 log.error("Failed to load yaml file {}", yamlFileName, e);
3464 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR,
3465 yamlFileName, e.getMessage());
3466 return Either.right(responseFormat);
3469 Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate,
3470 ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
3471 if (toscaElementEither.isRight()) {
3472 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3473 return Either.right(responseFormat);
3476 Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName,
3477 mappedToscaTemplate, resource);
3478 if (createInputsEither.isRight()) {
3479 ResponseFormat responseFormat = createInputsEither.right().value();
3480 return Either.right(responseFormat);
3483 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(
3484 yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
3485 if (uploadResInstancesEither.isRight()) {
3486 ResponseFormat responseFormat = uploadResInstancesEither.right().value();
3487 return Either.right(responseFormat);
3490 Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName,
3491 mappedToscaTemplate, resource);
3492 if (createGroupsFromYaml.isRight()) {
3493 ResponseFormat responseFormat = createGroupsFromYaml.right().value();
3494 return Either.right(responseFormat);
3497 ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
3498 parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
3499 parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
3500 parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
3502 return Either.left(parsedToscaYamlInfo);
3505 private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource,
3506 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
3507 Map<String, Resource> nodeNamespaceMap) {
3509 Either<Resource, ResponseFormat> eitherResource = null;
3510 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3511 if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
3512 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3514 return Either.right(responseFormat);
3517 Map<String, Resource> existingnodeTypeMap = new HashMap<>();
3518 if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) {
3519 nodeNamespaceMap.entrySet().stream()
3520 .forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
3523 Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet()
3525 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3526 while (nodesInfoValue.hasNext()) {
3527 log.debug("*************Going to create resource instances {}", yamlName);
3528 Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
3529 UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
3531 // updating type if the type is node type name - we need to take the
3533 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
3534 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3535 uploadComponentInstanceInfo
3536 .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
3539 eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
3540 existingnodeTypeMap);
3541 if (eitherResource.isRight()) {
3542 return eitherResource;
3544 Resource refResource = eitherResource.left().value();
3546 ComponentInstance componentInstance = new ComponentInstance();
3548 componentInstance.setComponentUid(refResource.getUniqueId());
3550 ComponentTypeEnum containerComponentType = resource.getComponentType();
3551 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
3553 if (containerNodeType.equals(NodeTypeEnum.Resource)
3554 && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
3555 && MapUtils.isNotEmpty(refResource.getCapabilities())) {
3556 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
3557 Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(
3558 refResource.getUniqueId(), refResource.getCapabilities(),
3559 uploadComponentInstanceInfo.getCapabilities());
3560 if (getValidComponentInstanceCapabilitiesRes.isRight()) {
3561 return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
3563 componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
3566 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
3568 "createResourceInstances - not found lates version for resource instance with name {} and type ",
3569 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3570 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3571 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3572 return Either.right(responseFormat);
3574 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
3575 componentInstance.setName(uploadComponentInstanceInfo.getName());
3576 componentInstance.setIcon(origResource.getIcon());
3578 resourcesInstancesMap.put(componentInstance, origResource);
3581 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
3583 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
3584 resourcesInstancesMap, false);
3585 if (status != null && status != StorageOperationStatus.OK) {
3586 log.debug("Failed to add component instances to container component {}", resource.getName());
3587 ResponseFormat responseFormat = componentsUtils
3588 .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
3589 eitherResource = Either.right(responseFormat);
3590 return eitherResource;
3595 log.debug("*************Going to get resource {}", resource.getUniqueId());
3596 ComponentParametersView parametersView = new ComponentParametersView();
3597 parametersView.disableAll();
3598 parametersView.setIgnoreComponentInstances(false);
3599 parametersView.setIgnoreUsers(false);
3600 parametersView.setIgnoreInputs(false); // inputs are read when creating
3601 // property values on instances
3602 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
3603 .getToscaElement(resource.getUniqueId(), parametersView);
3604 log.debug("*************finished to get resource {}", resource.getUniqueId());
3605 if (eitherGerResource.isRight()) {
3606 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
3607 componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
3609 return Either.right(responseFormat);
3613 if (eitherGerResource.left().value().getComponentInstances() == null
3614 || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
3616 log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
3617 BeEcompErrorManager.getInstance().logBeDaoSystemError(
3618 "Error when create resource inctanse from csar. ComponentInstances list empty");
3619 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3620 return Either.right(responseFormat);
3624 return Either.left(eitherGerResource.left().value());
3627 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
3628 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
3629 for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
3630 if (originCapabilities.containsKey(currEntry.getKey())) {
3631 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
3634 for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
3635 capabilities.getValue().stream().forEach(cap -> {
3636 if (uploadedCapabilities.containsKey(cap.getName())) {
3637 uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
3638 c.setName(cap.getName());
3639 c.setType(cap.getType());
3648 private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName,
3649 UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
3651 "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
3652 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3653 Resource refResource = null;
3654 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
3655 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
3657 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
3658 .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
3659 if (findResourceEither.isRight()) {
3661 "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
3662 uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3663 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3664 componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
3665 return Either.right(responseFormat);
3667 refResource = findResourceEither.left().value();
3668 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
3670 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
3671 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3673 "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
3674 refResource.getName(), componentState);
3675 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
3676 refResource.getComponentType().getValue(), refResource.getName(), componentState);
3677 return Either.right(responseFormat);
3680 if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
3681 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
3682 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
3683 yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3684 return Either.right(responseFormat);
3686 return Either.left(refResource);
3689 private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(
3690 String yamlFileName, Map<String, Object> toscaJson, Resource resource,
3691 Map<String, String> createdNodesToscaResourceNames) {
3692 Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
3693 Map<String, Object> substitutionMappings = null;
3694 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
3695 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils
3696 .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
3697 Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils
3698 .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
3699 if (eitherSubstitutionMappings.isLeft()) {
3700 substitutionMappings = eitherSubstitutionMappings.left().value();
3702 if (eitherNodesTemlates.isLeft()) {
3703 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
3705 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
3706 while (nodesNameValue.hasNext()) {
3707 Entry<String, Object> nodeNameValue = nodesNameValue.next();
3708 Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(
3709 nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
3710 if (eitherNode.isRight()) {
3711 log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(),
3712 resource.getName());
3713 return Either.right(eitherNode.right().value());
3715 UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
3716 moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
3722 if (moduleComponentInstances.isEmpty()) {
3723 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
3725 return Either.right(responseFormat);
3731 @SuppressWarnings("unchecked")
3732 private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(
3733 Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings,
3734 Map<String, String> createdNodesToscaResourceNames) {
3736 UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
3737 Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
3738 nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
3740 if (nodeTemplateJsonEntry.getValue() instanceof String) {
3741 String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
3742 nodeTemplateInfo.setType(nodeTemplateJsonString);
3743 } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
3744 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
3746 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
3747 String toscaResourceType = (String) nodeTemplateJsonMap
3748 .get(ToscaTagNamesEnum.TYPE.getElementName());
3749 if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
3750 toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
3752 nodeTemplateInfo.setType(toscaResourceType);
3755 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
3756 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(
3757 nodeTemplateInfo, nodeTemplateJsonMap);
3758 if (regResponse.isRight())
3759 return Either.right(regResponse.right().value());
3760 if (regResponse.left().value().size() > 0) {
3761 nodeTemplateInfo.setRequirements(regResponse.left().value());
3765 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
3766 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(
3767 nodeTemplateInfo, nodeTemplateJsonMap);
3768 if (eitherCapRes.isRight())
3769 return Either.right(eitherCapRes.right().value());
3770 if (eitherCapRes.left().value().size() > 0) {
3771 nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
3774 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
3775 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(
3776 nodeTemplateJsonMap);
3777 if (regResponse.isRight())
3778 return Either.right(regResponse.right().value());
3779 if (regResponse.left().value().size() > 0) {
3780 nodeTemplateInfo.setProperties(regResponse.left().value());
3783 if (substitutionMappings != null) {
3784 if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
3785 Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(
3786 nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings
3787 .get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
3788 if (getCapNamesToUpdateRes.isRight())
3789 return Either.right(getCapNamesToUpdateRes.right().value());
3790 if (getCapNamesToUpdateRes.left().value().size() > 0) {
3791 nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
3794 if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
3795 Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(
3796 nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings
3797 .get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
3798 if (getReqNamesToUpdateRes.isRight())
3799 return Either.right(getReqNamesToUpdateRes.right().value());
3800 if (getReqNamesToUpdateRes.left().value().size() > 0) {
3801 nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
3807 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
3810 } catch (Exception e) {
3811 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
3812 log.debug("error when creating capability, message:{}", e.getMessage(), e);
3813 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
3819 private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo,
3820 Map<String, List<String>> elements) {
3821 Either<Map<String, String>, ResponseFormat> response;
3823 Map<String, String> namesToUpdate = elements.entrySet().stream()
3824 .filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName()))
3825 .collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
3826 response = Either.left(namesToUpdate);
3827 } catch (Exception e) {
3828 log.debug("The exception occurred upon adding names to update for instance {}: ", nodeTemplateInfo.getName(), e);
3829 response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3834 @SuppressWarnings("unchecked")
3835 private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(
3836 Map<String, Object> nodeTemplateJsonMap) {
3837 Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
3838 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
3839 Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils
3840 .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
3841 if (toscaProperties.isLeft()) {
3842 Map<String, Object> jsonProperties = toscaProperties.left().value();
3843 for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
3845 String propName = jsonPropObj.getKey();
3846 Object propValue = jsonPropObj.getValue();
3848 if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
3849 log.trace("Ignore property value {}.", propName);
3853 if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
3854 log.trace("Ignore property value {}.", propName);
3857 if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
3858 log.trace("Ignore property value {}.", propName);
3862 if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
3863 log.trace("Ignore property value {}.", propName);
3867 if (valueContainsPattern(GET_ATTRIBUTE_PATTERN, propValue)) {
3868 log.trace("Ignore property value {}.", propName);
3872 UploadPropInfo propertyDef = new UploadPropInfo();
3873 propertyDef.setValue(propValue);
3874 propertyDef.setName(propName);
3875 if (propValue instanceof Map) {
3876 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
3877 propertyDef.setType(((Map<String, Object>) propValue)
3878 .get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
3881 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
3882 || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType())
3883 .contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
3884 createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
3887 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
3888 propertyDef.setDescription(((Map<String, Object>) propValue)
3889 .get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
3891 if (((Map<String, Object>) propValue)
3892 .containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
3893 propertyDef.setValue(((Map<String, Object>) propValue)
3894 .get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
3896 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
3897 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue)
3898 .get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
3900 propertyDef.setValue(propValue);
3902 } else if (propValue instanceof List) {
3903 List<Object> propValueList = (List<Object>) propValue;
3905 createInputPropList(propertyDef, propValueList);
3906 propertyDef.setValue(propValue);
3909 if (moduleProp.containsKey(propName)) {
3910 moduleProp.get(propName).add(propertyDef);
3912 List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
3913 list.add(propertyDef);
3914 moduleProp.put(propName, list);
3921 @SuppressWarnings("unchecked")
3922 private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
3923 for (Object objValue : propValueList) {
3925 if (objValue instanceof Map) {
3926 Map<String, Object> objMap = (Map<String, Object>) objValue;
3927 if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
3928 createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
3930 Set<String> keys = objMap.keySet();
3931 for (String key : keys) {
3932 Object value = objMap.get(key);
3933 if (value instanceof Map) {
3934 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
3936 } else if (value instanceof List) {
3937 List<Object> propSubValueList = (List<Object>) value;
3939 createInputPropList(propertyDef, propSubValueList);
3945 } else if (objValue instanceof List) {
3946 List<Object> propSubValueList = (List<Object>) objValue;
3948 createInputPropList(propertyDef, propSubValueList);
3955 @SuppressWarnings("unchecked")
3956 private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue,
3957 UploadPropInfo propertyDef) {
3959 if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
3960 Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
3961 GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
3962 List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
3963 if (getInputs == null) {
3964 getInputs = new ArrayList<GetInputValueDataDefinition>();
3966 if (getInput instanceof String) {
3968 getInputInfo.setInputName((String) getInput);
3969 getInputInfo.setPropName(propName);
3971 } else if (getInput instanceof List) {
3972 List<Object> getInputList = (List<Object>) getInput;
3973 getInputInfo.setPropName(propName);
3974 getInputInfo.setInputName((String) getInputList.get(0));
3975 if (getInputList.size() > 1) {
3976 Object indexObj = getInputList.get(1);
3977 if (indexObj instanceof Integer) {
3978 getInputInfo.setIndexValue((Integer) indexObj);
3979 } else if (indexObj instanceof Float) {
3980 int index = ((Float) indexObj).intValue();
3981 getInputInfo.setIndexValue(index);
3982 } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj)
3983 .containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
3984 Object index = ((Map<String, Object>) indexObj)
3985 .get(ToscaTagNamesEnum.GET_INPUT.getElementName());
3986 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
3987 getInputInfoIndex.setInputName((String) index);
3988 getInputInfoIndex.setPropName(propName);
3989 getInputInfo.setGetInputIndex(getInputInfoIndex);
3991 getInputInfo.setList(true);
3995 getInputs.add(getInputInfo);
3996 propertyDef.setGet_input(getInputs);
3997 propertyDef.setValue(propValue);
3999 Set<String> keys = propValue.keySet();
4000 for (String key : keys) {
4001 Object value = propValue.get(key);
4002 if (value instanceof Map) {
4003 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4005 } else if (value instanceof List) {
4006 List<Object> valueList = (List<Object>) value;
4007 for (Object o : valueList) {
4008 if (o instanceof Map) {
4009 createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
4022 private boolean valueContainsPattern(Pattern pattern, Object propValue) {
4024 log.debug("valueContainsToken value is {}", propValue);
4025 boolean result = false;
4026 if (propValue != null) {
4027 log.trace("valueContainspattern value is {}", propValue.getClass());
4028 Matcher matcher = pattern.matcher(propValue.toString());
4029 result = matcher.find();
4036 @SuppressWarnings("unchecked")
4037 private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(
4038 UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4039 Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
4040 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
4041 Either<List<Object>, ResultStatusEnum> requirementsListRes = ImportUtils
4042 .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4044 if (requirementsListRes.isLeft()) {
4045 for (Object jsonReqObj : requirementsListRes.left().value()) {
4046 String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
4047 Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName);
4048 Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo,
4049 moduleRequirements, reqJson, reqName);
4050 if (eitherCap.isRight()) {
4051 return Either.right(eitherCap.right().value());
4055 Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes = ImportUtils
4056 .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4057 if (requirementsMapRes.isLeft()) {
4058 for (Map.Entry<String, Object> entry : requirementsMapRes.left().value().entrySet()) {
4059 String reqName = entry.getKey();
4060 Object reqJson = entry.getValue();
4061 Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo,
4062 moduleRequirements, reqJson, reqName);
4063 if (eitherCap.isRight()) {
4064 return Either.right(eitherCap.right().value());
4072 private Either<UploadReqInfo, ResponseFormat> addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo,
4073 Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) {
4075 Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJson);
4076 if (eitherRequirement.isRight()) {
4077 log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
4078 return Either.right(eitherRequirement.right().value());
4080 UploadReqInfo requirementDef = eitherRequirement.left().value();
4081 requirementDef.setName(requirementName);
4082 if (moduleRequirements.containsKey(requirementName)) {
4083 moduleRequirements.get(requirementName).add(requirementDef);
4085 List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
4086 list.add(requirementDef);
4087 moduleRequirements.put(requirementName, list);
4090 return Either.left(eitherRequirement.left().value());
4093 @SuppressWarnings("unchecked")
4094 private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(
4095 UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4096 Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
4097 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
4098 Either<List<Object>, ResultStatusEnum> capabilitiesListRes = ImportUtils
4099 .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4100 if (capabilitiesListRes.isLeft()) {
4101 for (Object jsonCapObj : capabilitiesListRes.left().value()) {
4102 String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next();
4103 Object capJson = ((Map<String, Object>) jsonCapObj).get(key);
4104 Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap,
4106 if (eitherCap.isRight()) {
4107 return Either.right(eitherCap.right().value());
4111 Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes = ImportUtils
4112 .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4113 if (capabilitiesMapRes.isLeft()) {
4114 for (Map.Entry<String, Object> entry : capabilitiesMapRes.left().value().entrySet()) {
4115 String capName = entry.getKey();
4116 Object capJson = entry.getValue();
4117 Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo,
4118 moduleCap, capJson, capName);
4119 if (eitherCap.isRight()) {
4120 return Either.right(eitherCap.right().value());
4128 private Either<UploadCapInfo, ResponseFormat> addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo,
4129 Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
4131 Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJson);
4132 if (eitherCap.isRight()) {
4133 log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo);
4134 return Either.right(eitherCap.right().value());
4136 UploadCapInfo capabilityDef = eitherCap.left().value();
4137 capabilityDef.setKey(key);
4138 if (moduleCap.containsKey(key)) {
4139 moduleCap.get(key).add(capabilityDef);
4141 List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
4142 list.add(capabilityDef);
4143 moduleCap.put(key, list);
4146 return Either.left(eitherCap.left().value());
4149 @SuppressWarnings("unchecked")
4150 private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
4151 UploadCapInfo capTemplateInfo = new UploadCapInfo();
4152 Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
4154 if (capObject instanceof String) {
4155 String nodeTemplateJsonString = (String) capObject;
4156 capTemplateInfo.setNode(nodeTemplateJsonString);
4157 } else if (capObject instanceof Map) {
4158 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
4160 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4161 capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4163 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4164 capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4166 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
4167 Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils
4168 .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
4169 if (validSourceTypesRes.isLeft()) {
4170 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream()
4171 .map(o -> o.toString()).collect(Collectors.toList()));
4174 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4175 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(
4176 nodeTemplateJsonMap);
4177 if (regResponse.isRight())
4178 return Either.right(regResponse.right().value());
4179 if (!regResponse.left().value().isEmpty()) {
4180 List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
4181 regResponse.left().value().values().forEach(list -> properties.addAll(list));
4182 if (!properties.isEmpty())
4183 capTemplateInfo.setProperties(properties);
4190 @SuppressWarnings("unchecked")
4191 private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
4193 UploadReqInfo regTemplateInfo = new UploadReqInfo();
4194 Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
4196 if (regObject instanceof String) {
4197 String nodeTemplateJsonString = (String) regObject;
4198 regTemplateInfo.setNode(nodeTemplateJsonString);
4199 } else if (regObject instanceof Map) {
4200 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
4202 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4203 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4205 // US740820 Relate RIs according to capability name
4206 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
4207 regTemplateInfo.setCapabilityName(
4208 (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
4214 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
4215 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
4216 boolean forceCertificationAllowed) {
4218 Either<Resource, ResponseFormat> result = null;
4220 if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
4221 && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
4222 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4223 if (result.isRight()) {
4226 resource = result.left().value();
4228 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
4229 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
4230 resource, user, false, inTransaction, needLock);
4231 result = eitherPopulated.isLeft() ? Either.left(resource)
4232 : Either.right(eitherPopulated.right().value());
4235 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
4236 } catch (Exception e) {
4237 log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
4238 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4240 if (result == null || result.isRight()) {
4241 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4242 if (inTransaction == false) {
4243 log.debug("operation failed. do rollback");
4244 titanDao.rollback();
4246 } else if (inTransaction == false) {
4247 log.debug("operation success. do commit");
4253 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
4254 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4255 Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user,
4256 LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
4257 if (result.isLeft()) {
4258 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION,
4259 lifecycleChangeInfo, inTransaction, needLock);
4261 if (result.isLeft()) {
4262 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
4263 lifecycleChangeInfo, inTransaction, needLock);
4268 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
4269 LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4270 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
4275 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(
4276 Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
4277 CsarInfo csarInfo, String nodeName, boolean isNested) {
4279 // check if resource already exist
4280 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade
4281 .getLatestByName(resource.getName());
4282 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4285 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4287 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
4288 .getLatestByToscaResourceName(resource.getToscaResourceName());
4289 if (csarInfo != null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight()
4290 && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4291 latestByToscaName = toscaOperationFacade
4292 .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(),
4293 csarInfo.getVfResourceName(), nodeName).getRight());
4295 if (latestByToscaName.isLeft()) {
4296 log.debug("validate derived before update");
4297 Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
4298 latestByToscaName.left().value(), resource,
4299 ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion()));
4300 if (eitherValidation.isRight()) {
4301 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
4303 result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user,
4304 isNormative, needLock, isNested);
4308 if (result == null && latestByToscaName.isRight()
4309 && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4310 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
4311 } else if (result == null) {
4312 StorageOperationStatus status = latestByName.right().value();
4313 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
4314 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4315 log.debug("resource already exist {}. status={}", resource.getName(), status);
4316 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
4317 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
4318 result = Either.right(responseFormat);
4324 else if (latestByName.isLeft()) {
4325 result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock,
4331 StorageOperationStatus status = latestByName.right().value();
4332 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
4333 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4334 componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
4335 componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
4336 result = Either.right(responseFormat);
4342 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource,
4343 User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
4344 log.debug("resource with name {} does not exist. create new resource", resource.getName());
4345 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user,
4346 AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
4347 if (response.isRight()) {
4348 return Either.right(response.right().value());
4350 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user,
4351 AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
4352 if (createResponse.isRight()) {
4353 return Either.right(createResponse.right().value());
4355 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(),
4356 ActionStatus.CREATED);
4357 ASDCKpiApi.countImportResourcesKPI();
4358 return Either.left(resourcePair);
4363 public boolean isResourceExist(String resourceName) {
4364 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
4365 return latestByName.isLeft();
4368 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(
4369 Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
4371 String lockedResourceId = oldResource.getUniqueId();
4372 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
4373 oldResource.getVersion(), oldResource.getLifecycleState());
4374 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4377 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
4378 "Update Resource by Import");
4379 if (lockResult.isRight()) {
4380 return Either.right(lockResult.right().value());
4384 Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user,
4385 inTransaction, false);
4386 if (prepareResourceForUpdate.isRight()) {
4387 ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
4388 log.info("resource {} cannot be updated. reason={}", lockedResourceId,
4389 responseFormat.getFormattedMessage());
4390 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4391 ResourceAuditData.newBuilder()
4392 .state(oldResource.getLifecycleState().name())
4393 .version(oldResource.getVersion())
4395 result = Either.right(prepareResourceForUpdate.right().value());
4398 oldResource = prepareResourceForUpdate.left().value();
4400 mergeOldResourceMetadataWithNew(oldResource, newResource);
4402 Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource,
4403 newResource, inTransaction, isNested);
4404 if (validateFieldsResponse.isRight()) {
4405 result = Either.right(validateFieldsResponse.right().value());
4409 validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource,
4410 AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
4411 if (validateFieldsResponse.isRight()) {
4412 return Either.right(validateFieldsResponse.right().value());
4415 // contact info normalization
4416 newResource.setContactId(newResource.getContactId().toLowerCase());
4417 // non-updatable fields
4418 newResource.setCreatorUserId(user.getUserId());
4419 newResource.setCreatorFullName(user.getFullName());
4420 newResource.setLastUpdaterUserId(user.getUserId());
4421 newResource.setLastUpdaterFullName(user.getFullName());
4422 newResource.setUniqueId(oldResource.getUniqueId());
4423 newResource.setVersion(oldResource.getVersion());
4424 newResource.setInvariantUUID(oldResource.getInvariantUUID());
4425 newResource.setLifecycleState(oldResource.getLifecycleState());
4426 newResource.setUUID(oldResource.getUUID());
4427 newResource.setNormalizedName(oldResource.getNormalizedName());
4428 newResource.setSystemName(oldResource.getSystemName());
4429 if (oldResource.getCsarUUID() != null) {
4430 newResource.setCsarUUID(oldResource.getCsarUUID());
4432 if (oldResource.getImportedToscaChecksum() != null) {
4433 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
4435 newResource.setAbstract(oldResource.isAbstract());
4437 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
4438 newResource.setDerivedFrom(oldResource.getDerivedFrom());
4440 if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
4441 newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
4443 if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
4444 newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
4446 // TODO rhalili: handle artifacts here (delete from old resource and
4448 // TODO rbetzer: remove after migration - in case of resources
4449 // created without tosca artifacts - add the placeholders
4450 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
4451 setToscaArtifactsPlaceHolders(newResource, user);
4453 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
4454 .overrideComponent(newResource, oldResource);
4456 if (overrideResource.isRight()) {
4457 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4458 componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
4459 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
4461 result = Either.right(responseFormat);
4465 log.debug("Resource updated successfully!!!");
4466 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4467 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
4468 ResourceAuditData.newBuilder()
4469 .state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
4472 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(),
4474 result = Either.left(resourcePair);
4477 if (result == null || result.isRight()) {
4478 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4479 log.debug("operation failed. do rollback");
4480 titanDao.rollback();
4481 } else if (inTransaction == false) {
4482 log.debug("operation success. do commit");
4485 if (needLock == true) {
4486 log.debug("unlock resource {}", lockedResourceId);
4487 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4494 * Merge old resource with new. Keep old category and vendor name without
4497 * @param oldResource
4498 * @param newResource
4500 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4502 // keep old category and vendor name without change
4503 // merge the rest of the resource metadata
4504 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4505 newResource.setTags(oldResource.getTags());
4508 if (newResource.getDescription() == null) {
4509 newResource.setDescription(oldResource.getDescription());
4512 if (newResource.getVendorRelease() == null) {
4513 newResource.setVendorRelease(oldResource.getVendorRelease());
4516 if (newResource.getResourceVendorModelNumber() == null) {
4517 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
4520 if (newResource.getContactId() == null) {
4521 newResource.setContactId(oldResource.getContactId());
4524 newResource.setCategories(oldResource.getCategories());
4525 if (newResource.getVendorName() == null) {
4526 newResource.setVendorName(oldResource.getVendorName());
4530 private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user,
4531 boolean inTransaction, boolean needLock) {
4533 Either<Resource, ResponseFormat> result = Either.left(latestResource);
4534 // check if user can edit resource
4535 if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
4537 Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(
4538 latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
4539 new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
4540 result = changeState;
4546 public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user,
4547 AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
4549 Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource,
4550 actionEnum, inTransaction);
4551 if (eitherValidation.isRight()) {
4552 return Either.right(eitherValidation.right().value());
4555 eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum,
4557 if (eitherValidation.isRight()) {
4558 return Either.right(eitherValidation.right().value());
4560 eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
4561 if (eitherValidation.isRight()) {
4562 return Either.right(eitherValidation.right().value());
4564 eitherValidation = validateResourceType(user, resource, actionEnum);
4565 if (eitherValidation.isRight()) {
4566 return Either.right(eitherValidation.right().value());
4569 resource.setCreatorUserId(user.getUserId());
4570 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4571 resource.setContactId(resource.getContactId().toLowerCase());
4572 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
4573 String resourceSystemName;
4574 if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
4575 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
4577 resourceSystemName = resource.getSystemName();
4579 resource.setToscaResourceName(CommonBeUtils
4580 .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
4583 // Generate invariant UUID - must be here and not in operation since it
4584 // should stay constant during clone
4586 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4587 resource.setInvariantUUID(invariantUUID);
4589 return Either.left(resource);
4592 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
4593 AuditingActionEnum actionEnum) {
4594 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4595 if (resource.getResourceType() == null) {
4596 log.debug("Invalid resource type for resource");
4597 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4598 eitherResult = Either.right(errorResponse);
4599 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4601 return eitherResult;
4604 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
4605 AuditingActionEnum actionEnum) {
4606 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4607 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
4608 log.debug("validate interface lifecycle Types Exist");
4609 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
4610 while (intItr.hasNext() && eitherResult.isLeft()) {
4611 InterfaceDefinition interfaceDefinition = intItr.next();
4612 String intType = interfaceDefinition.getUniqueId();
4613 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
4614 .getInterface(intType);
4615 if (eitherCapTypeFound.isRight()) {
4616 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4617 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
4618 "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
4619 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
4620 intType, resource.getName());
4621 BeEcompErrorManager.getInstance()
4622 .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4623 log.debug("request to data model failed with error: {}",
4624 eitherCapTypeFound.right().value().name());
4627 ResponseFormat errorResponse = componentsUtils
4628 .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4629 eitherResult = Either.right(errorResponse);
4630 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4635 return eitherResult;
4638 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
4639 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4640 boolean inTransaction) {
4642 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4643 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
4644 log.debug("validate capability Types Exist - capabilities section");
4646 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
4648 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
4649 eitherResult, typeEntry, inTransaction);
4650 if (eitherResult.isRight()) {
4651 return Either.right(eitherResult.right().value());
4656 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
4657 log.debug("validate capability Types Exist - requirements section");
4658 for (String type : resource.getRequirements().keySet()) {
4659 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
4660 resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
4661 if (eitherResult.isRight()) {
4662 return Either.right(eitherResult.right().value());
4667 return eitherResult;
4670 // @param typeObject- the object to which the validation is done
4671 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4672 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
4673 AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4674 boolean inTransaction) {
4675 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4676 .getCapabilityType(type, inTransaction);
4677 if (eitherCapTypeFound.isRight()) {
4678 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4679 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
4680 "Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
4681 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
4682 resource.getName());
4683 BeEcompErrorManager.getInstance()
4684 .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
4686 log.debug("Trying to get capability type {} failed with error: {}", type,
4687 eitherCapTypeFound.right().value().name());
4688 ResponseFormat errorResponse = null;
4690 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4692 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
4694 eitherResult = Either.right(errorResponse);
4695 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4697 return eitherResult;
4700 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
4701 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
4702 Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
4703 boolean inTransaction) {
4704 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
4705 .getCapabilityType(typeEntry.getKey(), inTransaction);
4706 if (eitherCapTypeFound.isRight()) {
4707 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4708 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
4709 "Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
4710 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
4711 typeEntry.getKey(), resource.getName());
4712 BeEcompErrorManager.getInstance()
4713 .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
4715 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
4716 eitherCapTypeFound.right().value().name());
4717 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
4718 typeEntry.getKey());
4719 eitherResult = Either.right(errorResponse);
4720 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
4722 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4723 if (capabilityTypeDefinition.getProperties() != null) {
4724 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4725 List<ComponentInstanceProperty> properties = capDef.getProperties();
4726 if (properties == null || properties.isEmpty()) {
4727 properties = new ArrayList<ComponentInstanceProperty>();
4728 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4729 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4730 properties.add(newProp);
4733 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4734 PropertyDefinition porpFromDef = prop.getValue();
4735 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4736 for (ComponentInstanceProperty cip : properties) {
4737 if (!cip.getName().equals(porpFromDef.getName())) {
4738 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
4739 propsToAdd.add(newProp);
4742 if (!propsToAdd.isEmpty()) {
4743 properties.addAll(propsToAdd);
4747 capDef.setProperties(properties);
4750 return eitherResult;
4753 public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user,
4754 AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
4757 // lock new resource name in order to avoid creation resource with same
4759 if (inTransaction == false) {
4760 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
4762 if (lockResult.isRight()) {
4763 ResponseFormat responseFormat = lockResult.right().value();
4764 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
4765 return Either.right(responseFormat);
4768 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4771 if (resource.deriveFromGeneric()) {
4772 Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(resource);
4773 if (genericResourceEither.isRight())
4774 return genericResourceEither;
4777 Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative,
4779 if (respStatus.isLeft()) {
4780 componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
4781 respStatus.left().value(), actionEnum);
4782 ASDCKpiApi.countCreatedResourcesKPI();
4784 componentsUtils.auditResource(respStatus.right().value(), user, resource, actionEnum);
4788 if (inTransaction == false) {
4789 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
4790 NodeTypeEnum.Resource);
4795 private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum) {
4796 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
4797 componentsUtils.auditResource(responseFormat, user, persistedResource, actionEnum);
4800 private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user,
4801 boolean isNormative, boolean inTransaction) {
4802 // validate resource name uniqueness
4803 log.debug("validate resource name");
4804 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
4805 resource.getName(), resource.getResourceType(), resource.getComponentType());
4806 if (eitherValidation.isRight()) {
4807 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
4808 eitherValidation.right().value());
4809 ResponseFormat errorResponse = componentsUtils
4810 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
4811 return Either.right(errorResponse);
4813 if (eitherValidation.left().value()) {
4814 log.debug("resource with name: {}, already exists", resource.getName());
4815 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
4816 ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4817 return Either.right(errorResponse);
4820 log.debug("send resource {} to dao for create", resource.getName());
4822 createArtifactsPlaceHolderData(resource, user);
4828 log.debug("enrich resource with creator, version and state");
4829 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
4830 resource.setVersion(INITIAL_VERSION);
4831 resource.setHighestVersion(true);
4832 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
4833 resource.setAbstract(false);
4836 Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade
4837 .createToscaComponent(resource);
4838 if (createToscaElement.isLeft()) {
4839 return Either.left(createToscaElement.left().value());
4842 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
4843 componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
4845 return Either.right(responseFormat);
4848 private void createArtifactsPlaceHolderData(Resource resource, User user) {
4849 // create mandatory artifacts
4851 // TODO it must be removed after that artifact uniqueId creation will be
4852 // moved to ArtifactOperation
4854 setInformationalArtifactsPlaceHolder(resource, user);
4855 setDeploymentArtifactsPlaceHolder(resource, user);
4856 setToscaArtifactsPlaceHolders(resource, user);
4859 @SuppressWarnings("unchecked")
4861 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
4862 Resource resource = (Resource) component;
4863 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
4864 if (artifactMap == null) {
4865 artifactMap = new HashMap<String, ArtifactDefinition>();
4867 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4868 .getConfiguration().getDeploymentResourceArtifacts();
4869 if (deploymentResourceArtifacts != null) {
4870 Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
4871 while (iterator.hasNext()) {
4872 Entry<String, Object> currEntry = iterator.next();
4873 boolean shouldCreateArtifact = true;
4874 Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
4875 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
4876 if (object != null) {
4877 List<String> artifactTypes = (List<String>) object;
4878 if (!artifactTypes.contains(resource.getResourceType().name())) {
4879 shouldCreateArtifact = false;
4883 log.info("resource types for artifact placeholder {} were not defined. default is all resources",
4884 currEntry.getKey());
4886 if (shouldCreateArtifact) {
4887 if (artifactsBusinessLogic != null) {
4888 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4889 resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(),
4890 user, ArtifactGroupTypeEnum.DEPLOYMENT);
4891 if (artifactDefinition != null
4892 && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
4893 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4898 resource.setDeploymentArtifacts(artifactMap);
4901 @SuppressWarnings("unchecked")
4902 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
4903 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
4904 if (artifactMap == null) {
4905 artifactMap = new HashMap<String, ArtifactDefinition>();
4907 String resourceUniqueId = resource.getUniqueId();
4908 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
4909 .getExcludeResourceCategory();
4910 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
4911 .getExcludeResourceType();
4912 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
4913 .getConfiguration().getInformationalResourceArtifacts();
4914 List<CategoryDefinition> categories = resource.getCategories();
4915 boolean isCreateArtifact = true;
4916 if (exludeResourceCategory != null) {
4917 String category = categories.get(0).getName();
4918 for (String exlude : exludeResourceCategory) {
4919 if (exlude.equalsIgnoreCase(category)) {
4920 isCreateArtifact = false;
4926 if (isCreateArtifact && exludeResourceType != null) {
4927 String resourceType = resource.getResourceType().name();
4928 for (String type : exludeResourceType) {
4929 if (type.equalsIgnoreCase(resourceType)) {
4930 isCreateArtifact = false;
4937 if (informationalResourceArtifacts != null && isCreateArtifact) {
4938 Set<String> keys = informationalResourceArtifacts.keySet();
4939 for (String informationalResourceArtifactName : keys) {
4940 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
4941 .get(informationalResourceArtifactName);
4942 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
4943 resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
4944 ArtifactGroupTypeEnum.INFORMATIONAL);
4945 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
4949 resource.setArtifacts(artifactMap);
4959 public ResponseFormat deleteResource(String resourceId, User user) {
4960 ResponseFormat responseFormat;
4961 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
4962 if (eitherCreator.isRight()) {
4963 return eitherCreator.right().value();
4966 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
4967 if (resourceStatus.isRight()) {
4968 log.debug("failed to get resource {}", resourceId);
4969 return componentsUtils
4970 .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
4973 Resource resource = resourceStatus.left().value();
4975 StorageOperationStatus result = StorageOperationStatus.OK;
4976 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
4977 if (lockResult.isRight()) {
4978 result = StorageOperationStatus.GENERAL_ERROR;
4979 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4984 result = markComponentToDelete(resource);
4985 if (result.equals(StorageOperationStatus.OK)) {
4986 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
4988 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
4989 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
4991 return responseFormat;
4994 if (result == null || !result.equals(StorageOperationStatus.OK)) {
4995 log.warn("operation failed. do rollback");
4996 titanDao.rollback();
4998 log.debug("operation success. do commit");
5001 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
5006 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
5007 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5008 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5009 if (eitherCreator.isRight()) {
5010 return eitherCreator.right().value();
5013 Resource resource = null;
5014 StorageOperationStatus result = StorageOperationStatus.OK;
5017 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
5018 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
5019 if (resourceStatus.isRight()) {
5020 log.debug("failed to get resource {} version {}", resourceName, version);
5021 return componentsUtils.getResponseFormatByResource(
5022 componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
5025 resource = resourceStatus.left().value();
5028 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5029 log.warn("operation failed. do rollback");
5030 titanDao.rollback();
5031 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5032 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
5034 log.debug("operation success. do commit");
5038 if (resource != null) {
5039 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
5041 if (lockResult.isRight()) {
5042 result = StorageOperationStatus.GENERAL_ERROR;
5043 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5046 result = markComponentToDelete(resource);
5047 if (!result.equals(StorageOperationStatus.OK)) {
5048 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5049 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5050 return responseFormat;
5054 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5055 log.warn("operation failed. do rollback");
5056 titanDao.rollback();
5058 log.debug("operation success. do commit");
5061 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
5064 return responseFormat;
5067 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
5070 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
5071 if (eitherCreator.isRight()) {
5072 return Either.right(eitherCreator.right().value());
5076 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
5077 if (storageStatus.isRight()) {
5078 log.debug("failed to get resource by id {}", resourceId);
5079 return Either.right(componentsUtils.getResponseFormatByResource(
5080 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
5082 if (!(storageStatus.left().value() instanceof Resource)) {
5083 return Either.right(componentsUtils.getResponseFormatByResource(
5084 componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
5086 return Either.left(storageStatus.left().value());
5090 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
5093 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
5094 if (resp.isRight()) {
5095 return Either.right(resp.right().value());
5098 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
5099 .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
5100 if (getResource.isRight()) {
5101 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
5102 return Either.right(componentsUtils.getResponseFormatByResource(
5103 componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
5105 return Either.left(getResource.left().value());
5109 * updateResourceMetadata
5111 * @param user - modifier data (userId)
5112 * @param inTransaction TODO
5113 * @param resourceIdToUpdate - the resource identifier
5114 * @param newResource
5115 * @return Either<Resource, responseFormat>
5117 public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
5118 Resource currentResource, User user, boolean inTransaction) {
5120 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
5121 if (resp.isRight()) {
5122 return Either.right(resp.right().value());
5125 log.debug("Get resource with id {}", resourceIdToUpdate);
5126 boolean needToUnlock = false;
5127 boolean rollbackNeeded = true;
5130 if (currentResource == null) {
5131 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
5132 .getToscaElement(resourceIdToUpdate);
5133 if (storageStatus.isRight()) {
5134 return Either.right(componentsUtils.getResponseFormatByResource(
5135 componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5138 currentResource = storageStatus.left().value();
5140 // verify that resource is checked-out and the user is the last
5142 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
5143 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
5147 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
5148 NodeTypeEnum.Resource);
5149 if (!lockResult.equals(StorageOperationStatus.OK)) {
5150 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
5151 NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
5152 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
5153 ResponseFormat responseFormat = componentsUtils
5154 .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
5155 return Either.right(responseFormat);
5158 needToUnlock = true;
5160 // critical section starts here
5161 // convert json to object
5163 // Update and updated resource must have a non-empty "derivedFrom"
5165 // This code is not called from import resources, because of root
5166 // VF "derivedFrom" should be null (or ignored)
5167 if (ModelConverter.isAtomicComponent(currentResource)) {
5168 Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null,
5170 if (derivedFromNotEmptyEither.isRight()) {
5171 log.debug("for updated resource {}, derived from field is empty", newResource.getName());
5172 return Either.right(derivedFromNotEmptyEither.right().value());
5175 derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
5176 if (derivedFromNotEmptyEither.isRight()) {
5177 log.debug("for current resource {}, derived from field is empty", currentResource.getName());
5178 return Either.right(derivedFromNotEmptyEither.right().value());
5181 newResource.setDerivedFrom(null);
5184 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
5185 user, currentResource, false, true);
5186 if (dataModelResponse.isRight()) {
5187 log.debug("failed to update resource metadata!!!");
5188 rollbackNeeded = true;
5189 return Either.right(dataModelResponse.right().value());
5192 log.debug("Resource metadata updated successfully!!!");
5193 rollbackNeeded = false;
5194 return Either.left(dataModelResponse.left().value());
5197 if (!inTransaction) {
5198 if (rollbackNeeded) {
5199 titanDao.rollback();
5206 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5211 private Either<List<GroupDefinition>, Boolean> updateComponentGroupName(String replacePattern, String with,
5212 List<GroupDefinition> oldGroup) {
5213 if (oldGroup == null || with == null || replacePattern == null || with.isEmpty() || replacePattern.isEmpty()) {
5214 if (log.isInfoEnabled())
5215 log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}",
5216 replacePattern, with, oldGroup == null ? null : " < size : " + oldGroup.size() + " >");
5217 return Either.right(false);
5219 List<GroupDefinition> list = oldGroup.stream().map(group -> new GroupDefinition(group))
5220 .collect(Collectors.toList());
5221 for (GroupDefinition group : list) {
5222 if (group != null && group.isSamePrefix(replacePattern)) {
5223 String prefix = group.getName().substring(0, replacePattern.length());
5224 String newGroupName = group.getName().replaceFirst(prefix, with);
5225 group.setName(newGroupName);
5228 return Either.left(list);
5231 private boolean isComponentNameChanged(Resource newResource, Resource oldResource) {
5232 if (newResource != null && oldResource != null) { // TODO - must protect
5233 // all chain against
5236 String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5237 String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5238 return !oldName.equals(futureName);
5243 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
5244 User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
5245 // region -> Update groups name for newResource
5246 if (isComponentNameChanged(currentResource, newResource)) {
5247 String replacePattern = Optional.ofNullable( // get currentResource
5250 Optional.ofNullable(
5251 Optional.ofNullable(currentResource).orElse(null).getComponentMetadataDefinition())
5252 .orElse(null).getMetadataDataDefinition())
5253 .orElse(null).getName();
5254 String with = Optional.ofNullable( // get newResource name from
5256 Optional.ofNullable(Optional.ofNullable(newResource).orElse(null).getComponentMetadataDefinition())
5257 .orElse(null).getMetadataDataDefinition())
5258 .orElse(null).getName();
5259 if (with != null && replacePattern != null) {
5260 Either<List<GroupDefinition>, Boolean> result = updateComponentGroupName(replacePattern, with,
5261 currentResource.getGroups());
5262 if (result.isLeft())
5263 newResource.setGroups((List<GroupDefinition>) result.left().value());
5268 Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource,
5269 newResource, inTransaction, false);
5270 if (validateResourceFields.isRight()) {
5271 return Either.right(validateResourceFields.right().value());
5273 // Setting last updater and uniqueId
5274 newResource.setContactId(newResource.getContactId().toLowerCase());
5275 newResource.setLastUpdaterUserId(user.getUserId());
5276 newResource.setUniqueId(resourceIdToUpdate);
5277 // Cannot set highest version through UI
5278 newResource.setHighestVersion(currentResource.isHighestVersion());
5279 newResource.setCreationDate(currentResource.getCreationDate());
5281 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
5282 newResource, user.getUserId(), shouldLock, inTransaction);
5284 if (processUpdateOfDerivedFrom.isRight()) {
5285 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
5286 return Either.right(processUpdateOfDerivedFrom.right().value());
5289 log.debug("send resource {} to dao for update", newResource.getUniqueId());
5290 if (newResource != null && newResource.getGroups() != null) {
5291 for (GroupDefinition group : newResource.getGroups()) {
5292 if (newResource.getComponentMetadataDefinition() != null
5293 && newResource.getComponentMetadataDefinition().getMetadataDataDefinition() != null)
5294 groupBusinessLogic.validateAndUpdateGroupMetadata(
5295 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
5296 user, ComponentTypeEnum.RESOURCE_INSTANCE, group, true, false);
5299 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5300 .updateToscaElement(newResource);
5302 if (dataModelResponse.isRight()) {
5303 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5304 componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
5305 return Either.right(responseFormat);
5306 } else if (dataModelResponse.left().value() == null) {
5307 log.debug("No response from updateResource");
5308 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5310 return Either.left(dataModelResponse.left().value());
5314 * validateResourceFieldsBeforeCreate
5316 * @param user - modifier data (userId)
5317 * @return Either<Boolean, ErrorResponse>
5319 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
5320 AuditingActionEnum actionEnum, boolean inTransaction) {
5321 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource,
5323 if (componentsFieldsValidation.isRight()) {
5324 return componentsFieldsValidation;
5328 // validate category
5329 log.debug("validate category");
5330 Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
5331 if (eitherValidation.isRight()) {
5332 return eitherValidation;
5335 // validate vendor name & release & model number
5336 log.debug("validate vendor name");
5337 eitherValidation = validateVendorName(user, resource, actionEnum);
5338 if (eitherValidation.isRight()) {
5339 return eitherValidation;
5342 log.debug("validate vendor release");
5343 eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
5344 if (eitherValidation.isRight()) {
5345 return eitherValidation;
5348 log.debug("validate resource vendor model number");
5349 eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
5350 if (eitherValidation.isRight()) {
5351 return eitherValidation;
5356 log.debug("validate cost");
5357 eitherValidation = validateCost(user, resource, actionEnum);
5358 if (eitherValidation.isRight()) {
5359 return eitherValidation;
5362 // validate licenseType
5363 log.debug("validate licenseType");
5364 eitherValidation = validateLicenseType(user, resource, actionEnum);
5365 if (eitherValidation.isRight()) {
5366 return eitherValidation;
5369 // validate template (derived from)
5370 log.debug("validate derived from");
5371 if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
5372 resource.setDerivedFrom(null);
5374 eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
5375 if (eitherValidation.isRight()) {
5376 return Either.right(eitherValidation.right().value());
5379 // warn about non-updatable fields
5380 checkComponentFieldsForOverrideAttempt(resource);
5381 String currentCreatorFullName = resource.getCreatorFullName();
5382 if (currentCreatorFullName != null) {
5383 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5386 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
5387 if (currentLastUpdaterFullName != null) {
5388 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5391 Long currentLastUpdateDate = resource.getLastUpdateDate();
5392 if (currentLastUpdateDate != null) {
5393 log.warn("Resource last update date is automatically set and cannot be updated");
5396 Boolean currentAbstract = resource.isAbstract();
5397 if (currentAbstract != null) {
5398 log.warn("Resource abstract is automatically set and cannot be updated");
5401 return Either.left(true);
5405 * validateResourceFieldsBeforeUpdate
5407 * @param currentResource - Resource object to validate
5409 * @return Either<Boolean, ErrorResponse>
5411 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource,
5412 Resource updateInfoResource, boolean inTransaction, boolean isNested) {
5414 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5416 // validate resource name
5417 log.debug("validate resource name before update");
5418 Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource,
5419 hasBeenCertified, isNested);
5420 if (eitherValidation.isRight()) {
5421 return eitherValidation;
5424 // validate description
5425 log.debug("validate description before update");
5426 eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
5427 if (eitherValidation.isRight()) {
5428 return eitherValidation;
5431 log.debug("validate icon before update");
5432 eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5433 if (eitherValidation.isRight()) {
5434 return eitherValidation;
5437 log.debug("validate tags before update");
5438 eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
5439 if (eitherValidation.isRight()) {
5440 return eitherValidation;
5443 log.debug("validate vendor name before update");
5444 eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
5445 if (eitherValidation.isRight()) {
5446 return eitherValidation;
5449 log.debug("validate resource vendor model number before update");
5450 eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
5451 if (eitherValidation.isRight()) {
5452 return eitherValidation;
5455 log.debug("validate vendor release before update");
5456 eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
5457 if (eitherValidation.isRight()) {
5458 return eitherValidation;
5461 log.debug("validate contact info before update");
5462 eitherValidation = validateContactId(null, updateInfoResource, null);
5463 if (eitherValidation.isRight()) {
5464 return eitherValidation;
5467 log.debug("validate derived before update");
5468 eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5469 if (eitherValidation.isRight()) {
5470 return eitherValidation;
5473 log.debug("validate category before update");
5474 eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5475 if (eitherValidation.isRight()) {
5476 return eitherValidation;
5479 // warn about non-updatable fields
5480 String currentResourceVersion = currentResource.getVersion();
5481 String updatedResourceVersion = updateInfoResource.getVersion();
5483 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
5484 log.warn("Resource version is automatically set and cannot be updated");
5487 String currentCreatorUserId = currentResource.getCreatorUserId();
5488 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
5490 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
5491 log.warn("Resource Creator UserId is automatically set and cannot be updated");
5494 String currentCreatorFullName = currentResource.getCreatorFullName();
5495 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
5497 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
5498 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5501 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
5502 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
5504 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
5505 log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
5508 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
5509 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
5511 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
5512 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5515 Long currentCreationDate = currentResource.getCreationDate();
5516 Long updatedCreationDate = updateInfoResource.getCreationDate();
5518 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
5519 log.warn("Resource Creation date is automatically set and cannot be updated");
5522 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
5523 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
5525 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
5526 log.warn("Resource last update date is automatically set and cannot be updated");
5529 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
5530 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
5532 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
5533 log.warn("Resource lifecycle state date is automatically set and cannot be updated");
5536 Boolean currentAbstract = currentResource.isAbstract();
5537 Boolean updatedAbstract = updateInfoResource.isAbstract();
5539 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
5540 log.warn("Resource abstract is automatically set and cannot be updated");
5543 Boolean currentHighestVersion = currentResource.isHighestVersion();
5544 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
5546 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
5547 log.warn("Resource highest version is automatically set and cannot be updated");
5550 String currentUuid = currentResource.getUUID();
5551 String updatedUuid = updateInfoResource.getUUID();
5553 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
5554 log.warn("Resource UUID is automatically set and cannot be updated");
5557 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
5558 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
5560 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
5561 log.warn("Resource Type cannot be updated");
5564 updateInfoResource.setResourceType(currentResource.getResourceType());
5566 String currentInvariantUuid = currentResource.getInvariantUUID();
5567 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
5569 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5570 log.warn("Resource invariant UUID is automatically set and cannot be updated");
5571 updateInfoResource.setInvariantUUID(currentInvariantUuid);
5573 return Either.left(true);
5577 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
5578 String resourceNameUpdated = updateInfoResource.getName();
5579 String resourceNameCurrent = currentResource.getName();
5580 if (resourceNameCurrent.equals(resourceNameUpdated))
5582 // In case of CVFC type we should support the case of old VF with CVFC
5583 // instances that were created without the "Cvfc" suffix
5584 return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
5585 resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
5588 private String addCvfcSuffixToResourceName(String resourceName) {
5589 return resourceName + "Cvfc";
5592 private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource,
5593 boolean hasBeenCertified, boolean isNested) {
5594 String resourceNameUpdated = updateInfoResource.getName();
5595 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
5596 if (isNested || !hasBeenCertified) {
5597 Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null,
5598 updateInfoResource, null);
5599 if (validateResourceNameResponse.isRight()) {
5600 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
5601 return Either.right(errorResponse);
5603 validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
5604 if (validateResourceNameResponse.isRight()) {
5605 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
5606 return Either.right(errorResponse);
5608 currentResource.setName(resourceNameUpdated);
5609 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5610 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5613 log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
5614 resourceNameUpdated);
5615 ResponseFormat errorResponse = componentsUtils
5616 .getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5617 return Either.right(errorResponse);
5620 return Either.left(true);
5623 private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource,
5624 boolean hasBeenCertified) {
5625 String iconUpdated = updateInfoResource.getIcon();
5626 String iconCurrent = currentResource.getIcon();
5627 if (!iconCurrent.equals(iconUpdated)) {
5628 if (!hasBeenCertified) {
5629 Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
5630 if (validateIcon.isRight()) {
5631 ResponseFormat errorResponse = validateIcon.right().value();
5632 return Either.right(errorResponse);
5635 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5636 ResponseFormat errorResponse = componentsUtils
5637 .getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5638 return Either.right(errorResponse);
5641 return Either.left(true);
5644 private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource,
5645 boolean hasBeenCertified) {
5646 String vendorNameUpdated = updateInfoResource.getVendorName();
5647 String vendorNameCurrent = currentResource.getVendorName();
5648 if (!vendorNameCurrent.equals(vendorNameUpdated)) {
5649 if(updateInfoResource.getResourceType().equals(ResourceTypeEnum.VF) && hasBeenCertified ){
5650 log.info("Vendor name {} cannot be updated once the resource has been certified once.",
5652 ResponseFormat errorResponse = componentsUtils
5653 .getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
5654 return Either.right(errorResponse);
5658 Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
5659 if (validateVendorName.isRight()) {
5660 ResponseFormat errorResponse = validateVendorName.right().value();
5661 return Either.right(errorResponse);
5665 return Either.left(true);
5668 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource,
5669 Resource updateInfoResource) {
5670 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
5671 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
5672 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
5673 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null,
5674 updateInfoResource, null);
5675 if (validateResourceVendorModelNumber.isRight()) {
5676 ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
5677 return Either.right(errorResponse);
5680 return Either.left(true);
5683 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
5684 boolean hasBeenCertified, boolean inTransaction) {
5685 Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null,
5687 if (validateCategoryName.isRight()) {
5688 ResponseFormat errorResponse = validateCategoryName.right().value();
5689 return Either.right(errorResponse);
5691 if (hasBeenCertified) {
5692 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
5693 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
5694 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
5695 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
5696 if (!currentCategory.getName().equals(updateCategory.getName())
5697 || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
5698 log.info("Category {} cannot be updated once the resource has been certified once.",
5699 currentResource.getCategories());
5700 ResponseFormat errorResponse = componentsUtils
5701 .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5702 return Either.right(errorResponse);
5705 return Either.left(true);
5708 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
5709 Resource updateInfoResource, boolean hasBeenCertified) {
5711 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5712 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5713 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5714 || updatedDerivedFrom.isEmpty()) {
5715 log.trace("Update normative types");
5716 return Either.left(true);
5719 String derivedFromCurrent = currentDerivedFrom.get(0);
5720 String derivedFromUpdated = updatedDerivedFrom.get(0);
5722 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5723 if (!hasBeenCertified) {
5724 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null,
5725 updateInfoResource, null);
5726 if (validateDerivedFromExistsEither.isRight()) {
5727 return validateDerivedFromExistsEither;
5730 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5731 currentResource, updateInfoResource, null);
5733 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
5734 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5735 return validateDerivedFromExtending;
5739 // For derived from, we must know whether it was actually changed,
5740 // otherwise we must do no action.
5741 // Due to changes it inflicts on data model (remove artifacts,
5742 // properties...), it's not like a flat field which can be
5743 // overwritten if not changed.
5744 // So we must indicate that derived from is not changed
5745 updateInfoResource.setDerivedFrom(null);
5747 return Either.left(true);
5750 private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
5751 Resource updateInfoResource, boolean hasBeenCertified) {
5753 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5754 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5755 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
5756 || updatedDerivedFrom.isEmpty()) {
5757 log.trace("Update normative types");
5758 return Either.left(true);
5761 String derivedFromCurrent = currentDerivedFrom.get(0);
5762 String derivedFromUpdated = updatedDerivedFrom.get(0);
5764 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5765 if (!hasBeenCertified) {
5766 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null,
5767 updateInfoResource, null);
5768 if (validateDerivedFromExistsEither.isRight()) {
5769 return validateDerivedFromExistsEither;
5772 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
5773 currentResource, updateInfoResource, null);
5775 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
5776 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5777 return validateDerivedFromExtending;
5781 return Either.left(true);
5784 private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource,
5785 AuditingActionEnum actionEnum) {
5787 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
5788 return Either.left(true);
5792 String templateName = resource.getDerivedFrom().get(0);
5794 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5795 .validateToscaResourceNameExists(templateName);
5796 if (dataModelResponse.isRight()) {
5797 StorageOperationStatus storageStatus = dataModelResponse.right().value();
5798 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5799 log.debug("request to data model failed with error: {}", storageStatus);
5800 ResponseFormat responseFormat = componentsUtils
5801 .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5802 log.trace("audit before sending response");
5803 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5804 return Either.right(responseFormat);
5805 } else if (!dataModelResponse.left().value()) {
5806 log.info("resource template with name: {}, does not exists", templateName);
5807 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5808 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5810 return Either.right(responseFormat);
5813 return Either.left(true);
5816 // Tal G for extending inheritance US815447
5817 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
5818 Resource updateInfoResource, AuditingActionEnum actionEnum) {
5819 String currentTemplateName = currentResource.getDerivedFrom().get(0);
5820 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
5822 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
5823 .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5824 if (dataModelResponse.isRight()) {
5825 StorageOperationStatus storageStatus = dataModelResponse.right().value();
5826 BeEcompErrorManager.getInstance()
5827 .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5828 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
5829 componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5830 log.trace("audit before sending response");
5831 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5832 return Either.right(responseFormat);
5835 if (!dataModelResponse.left().value()) {
5836 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
5837 currentTemplateName);
5838 ResponseFormat responseFormat = componentsUtils
5839 .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5840 componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
5842 return Either.right(responseFormat);
5845 return Either.left(true);
5848 public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource,
5849 AuditingActionEnum actionEnum) {
5850 log.debug("validate resource derivedFrom field");
5851 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
5852 || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
5853 log.info("derived from (template) field is missing for the resource");
5854 ResponseFormat responseFormat = componentsUtils
5855 .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5856 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5858 return Either.right(responseFormat);
5860 return Either.left(true);
5863 private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
5865 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
5866 .validateComponentNameExists(resource.getName(), resource.getResourceType(),
5867 resource.getComponentType());
5868 if (resourceOperationResponse.isLeft()) {
5869 if (!resourceOperationResponse.left().value()) {
5870 return Either.left(false);
5872 log.debug("resource with name: {}, already exists", resource.getName());
5873 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5874 ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
5875 resource.getName());
5876 return Either.right(errorResponse);
5879 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5880 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
5881 componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
5882 return Either.right(errorResponse);
5886 private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource,
5887 AuditingActionEnum actionEnum, boolean inTransaction) {
5889 List<CategoryDefinition> categories = resource.getCategories();
5890 if (categories == null || categories.size() == 0) {
5891 log.debug("Resource category is empty");
5892 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5893 ComponentTypeEnum.RESOURCE.getValue());
5894 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5895 return Either.right(responseFormat);
5897 if (categories.size() > 1) {
5898 log.debug("Must be only one category for resource");
5899 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5900 ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
5901 return Either.right(responseFormat);
5903 CategoryDefinition category = categories.get(0);
5904 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5905 if (subcategories == null || subcategories.size() == 0) {
5906 log.debug("Missinig subcategory for resource");
5907 ResponseFormat responseFormat = componentsUtils
5908 .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5909 return Either.right(responseFormat);
5911 if (subcategories.size() > 1) {
5912 log.debug("Must be only one sub category for resource");
5913 ResponseFormat responseFormat = componentsUtils
5914 .getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5915 return Either.right(responseFormat);
5918 SubCategoryDefinition subcategory = subcategories.get(0);
5920 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5921 log.debug("Resource category is empty");
5922 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
5923 ComponentTypeEnum.RESOURCE.getValue());
5924 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5925 return Either.right(responseFormat);
5927 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5928 log.debug("Resource category is empty");
5929 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
5930 ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5931 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5932 return Either.right(responseFormat);
5935 Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
5936 if (validateCategory.isRight()) {
5937 ResponseFormat responseFormat = validateCategory.right().value();
5938 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5939 return Either.right(responseFormat);
5942 return Either.left(true);
5945 private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category,
5946 SubCategoryDefinition subcategory, boolean inTransaction) {
5947 if (category != null && subcategory != null) {
5948 log.debug("validating resource category {} against valid categories list", category);
5949 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
5950 .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5951 if (categories.isRight()) {
5952 log.debug("failed to retrive resource categories from Titan");
5953 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
5954 return Either.right(responseFormat);
5956 List<CategoryDefinition> categoryList = categories.left().value();
5957 for (CategoryDefinition cat : categoryList) {
5958 if (cat.getName().equals(category.getName())) {
5959 for (SubCategoryDefinition subcat : cat.getSubcategories()) {
5960 if (subcat.getName().equals(subcategory.getName())) {
5961 return Either.left(true);
5965 "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
5966 subcategory, cat.getSubcategories());
5967 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5968 ComponentTypeEnum.RESOURCE.getValue()));
5971 log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
5972 category, categoryList);
5973 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
5974 ComponentTypeEnum.RESOURCE.getValue()));
5976 return Either.left(false);
5979 public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource,
5980 AuditingActionEnum actionEnum) {
5981 String vendorRelease = resource.getVendorRelease();
5983 log.debug("validate vendor relese name");
5984 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
5985 log.info("vendor relese name is missing.");
5986 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
5987 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
5988 return Either.right(errorResponse);
5991 Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
5992 if (validateVendorReleaseResponse.isRight()) {
5993 ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
5994 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
5996 return validateVendorReleaseResponse;
5999 public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
6000 if (vendorRelease != null) {
6001 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
6002 log.info("vendor release exceds limit.");
6003 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
6004 ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
6005 return Either.right(errorResponse);
6008 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
6009 log.info("vendor release is not valid.");
6010 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
6011 return Either.right(errorResponse);
6013 return Either.left(true);
6015 return Either.left(false);
6019 private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource,
6020 AuditingActionEnum actionEnum) {
6021 String vendorName = resource.getVendorName();
6022 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
6023 log.info("vendor name is missing.");
6024 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
6025 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
6026 return Either.right(errorResponse);
6029 Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
6030 if (validateVendorNameResponse.isRight()) {
6031 ResponseFormat responseFormat = validateVendorNameResponse.right().value();
6032 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
6034 return validateVendorNameResponse;
6038 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource,
6039 AuditingActionEnum actionEnum) {
6040 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
6041 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(
6042 resourceVendorModelNumber);
6043 if (validateResourceVendorModelNumber.isRight()) {
6044 ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
6045 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
6047 return validateResourceVendorModelNumber;
6051 private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
6052 if (vendorName != null) {
6053 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
6054 log.info("vendor name exceds limit.");
6055 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
6056 "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
6057 return Either.right(errorResponse);
6060 if (!ValidationUtils.validateVendorName(vendorName)) {
6061 log.info("vendor name is not valid.");
6062 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
6063 return Either.right(errorResponse);
6065 return Either.left(true);
6068 return Either.left(false);
6072 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
6073 if (StringUtils.isEmpty(resourceVendorModelNumber)) {
6074 return Either.left(true);
6076 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
6077 log.info("resource vendor model number exceeds limit.");
6078 ResponseFormat errorResponse = componentsUtils.getResponseFormat(
6079 ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
6080 "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
6081 return Either.right(errorResponse);
6083 // resource vendor model number is currently validated as vendor
6085 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
6086 log.info("resource vendor model number is not valid.");
6087 ResponseFormat errorResponse = componentsUtils
6088 .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
6089 return Either.right(errorResponse);
6091 return Either.left(true);
6096 private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
6097 String cost = resource.getCost();
6100 if (!ValidationUtils.validateCost(cost)) {
6101 log.debug("resource cost is invalid.");
6102 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6103 return Either.right(errorResponse);
6106 return Either.left(true);
6109 private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource,
6110 AuditingActionEnum actionEnum) {
6111 log.debug("validate licenseType");
6112 String licenseType = resource.getLicenseType();
6113 if (licenseType != null) {
6114 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
6116 if (!licenseTypes.contains(licenseType)) {
6117 log.debug("License type {} isn't configured");
6118 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6119 if (actionEnum != null) {
6120 // In update case, no audit is required
6121 componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
6123 return Either.right(responseFormat);
6126 return Either.left(true);
6129 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
6130 Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
6131 Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
6132 if (updatedResource.getDerivedFrom() != null) {
6133 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
6134 log.debug("1. Removing interface artifacts from graph");
6135 // Remove all interface artifacts of resource
6136 String resourceId = updatedResource.getUniqueId();
6137 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
6139 if (interfaces != null) {
6140 Collection<InterfaceDefinition> values = interfaces.values();
6141 for (InterfaceDefinition interfaceDefinition : values) {
6142 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
6144 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
6145 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
6146 if (operations != null) {
6147 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
6148 Operation operation = operationEntry.getValue();
6149 ArtifactDefinition implementation = operation.getImplementationArtifact();
6150 if (implementation != null) {
6151 String uniqueId = implementation.getUniqueId();
6152 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
6153 uniqueId, operationEntry.getKey(), interfaceType);
6154 // only thing that transacts and locks here
6155 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
6158 if (deleteArtifactByInterface.isRight()) {
6159 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
6160 if (!inTransaction) {
6161 titanDao.rollback();
6163 return Either.right(deleteArtifactByInterface.right().value());
6166 log.trace("No implementation found for operation {} - nothing to delete",
6167 operationEntry.getKey());
6171 log.trace("No operations found for interface type {}", interfaceType);
6175 log.debug("2. Removing properties");
6176 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
6177 .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
6179 if (findPropertiesOfNode.isRight()
6180 && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
6181 log.debug("Failed to remove all properties of resource");
6183 titanDao.rollback();
6184 return Either.right(componentsUtils.getResponseFormat(
6185 componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
6189 log.debug("Derived from wasn't changed during update");
6194 return Either.left(true);
6198 /**** Auditing *******************/
6200 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
6201 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
6202 .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
6204 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
6206 return webApplicationContext.getBean(class1);
6209 public ICapabilityTypeOperation getCapabilityTypeOperation() {
6210 return capabilityTypeOperation;
6213 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
6214 this.capabilityTypeOperation = capabilityTypeOperation;
6217 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
6218 log.debug("validate resource properties default values");
6219 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
6220 List<PropertyDefinition> properties = resource.getProperties();
6222 String innerType = null;
6223 if (properties != null) {
6224 for (PropertyDefinition property : properties) {
6225 if (!propertyOperation.isPropertyTypeValid(property)) {
6226 log.info("Invalid type for property");
6227 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
6228 ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
6229 eitherResult = Either.right(responseFormat);
6233 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
6234 applicationDataTypeCache);
6235 if (allDataTypes.isRight()) {
6236 return Either.right(allDataTypes.right().value());
6239 type = property.getType();
6240 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6241 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
6242 .isPropertyInnerTypeValid(property, allDataTypes.left().value());
6243 innerType = propertyInnerTypeValid.getLeft();
6244 if (!propertyInnerTypeValid.getRight().booleanValue()) {
6245 log.info("Invalid inner type for property");
6246 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
6247 ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
6248 eitherResult = Either.right(responseFormat);
6253 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
6254 log.info("Invalid default value for property");
6255 ResponseFormat responseFormat;
6256 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6257 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
6258 property.getName(), type, innerType, property.getDefaultValue());
6260 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
6261 property.getName(), type, property.getDefaultValue());
6263 eitherResult = Either.right(responseFormat);
6269 return eitherResult;
6273 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
6274 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
6278 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
6279 return componentInstanceBusinessLogic;
6282 private String getComponentTypeForResponse(Component component) {
6283 String componentTypeForResponse = "SERVICE";
6284 if (component instanceof Resource) {
6285 componentTypeForResponse = ((Resource) component).getResourceType().name();
6287 return componentTypeForResponse;
6290 private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName,
6291 Map<String, Object> toscaJson, Resource resource) {
6293 Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
6294 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
6296 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils
6297 .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
6298 if (eitherNodesTemlates.isLeft()) {
6299 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
6301 if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
6302 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
6303 while (nodesNameValue.hasNext()) {
6304 Entry<String, Object> groupNameValue = nodesNameValue.next();
6306 String groupName = groupNameValue.getKey();
6307 Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName,
6308 groupNameValue.getValue());
6309 if (eitherNode.isRight()) {
6310 String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:"
6311 + resource.getName();
6312 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message,
6313 ErrorSeverity.INFO);
6314 return Either.right(eitherNode.right().value());
6316 GroupDefinition groupDefinition = eitherNode.left().value();
6317 groups.put(groupName, groupDefinition);
6326 private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName,
6327 Map<String, Object> toscaJson, Resource resource) {
6329 Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
6330 if (inputs.isRight()) {
6331 String message = "Failed when creating inputs: for resource:" + resource.getName();
6332 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6333 Map<String, InputDefinition> resultMap = new HashMap<>();
6334 return Either.left(resultMap);
6338 Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
6343 @SuppressWarnings("unchecked")
6344 private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
6346 GroupDefinition groupInfo = new GroupDefinition();
6347 groupInfo.setName(groupName);
6348 Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
6351 if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
6352 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
6353 String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
6354 if (!StringUtils.isEmpty(groupType)) {
6355 groupInfo.setType(groupType);
6357 log.debug("The 'type' member is not found under group {}", groupName);
6359 .right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
6362 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
6363 groupInfo.setDescription(
6364 (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
6367 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
6368 Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
6369 if (members != null) {
6370 if (members instanceof List) {
6371 Map<String, String> membersLoaded = new HashMap<>();
6372 List<?> membersAsList = (List<?>) members;
6373 for (Object member : membersAsList) {
6374 membersLoaded.put(member.toString(), "");
6376 groupInfo.setMembers(membersLoaded);
6378 log.debug("The 'members' member is not of type list under group {}", groupName);
6380 .right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6385 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
6386 Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
6388 Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(
6389 properties, groupName, groupType);
6390 if (regResponse.isRight())
6391 return Either.right(regResponse.right().value());
6392 if (regResponse.left().value().size() > 0) {
6393 groupInfo.convertFromGroupProperties(regResponse.left().value());
6398 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6400 } catch (Exception e) {
6401 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
6402 log.debug("error when creating group, message:{}", e.getMessage(), e);
6403 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
6409 @SuppressWarnings("unchecked")
6410 private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties,
6411 String groupName, String groupType) {
6413 List<GroupProperty> result = new ArrayList<>();
6415 if (properties == null) {
6416 return Either.left(result);
6419 Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation
6420 .getLatestGroupTypeByType(groupType, true);
6422 if (groupTypeRes.isRight()) {
6423 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
6426 Map<String, PropertyDefinition> gtProperties = new HashMap<>();
6427 GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
6429 List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
6431 if (propertiesDef != null) {
6432 gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
6435 if (properties != null) {
6437 if (properties instanceof Map) {
6439 Map<String, Object> props = (Map<String, Object>) properties;
6440 for (Entry<String, Object> entry : props.entrySet()) {
6442 String propName = entry.getKey();
6443 Object value = entry.getValue();
6445 PropertyDefinition gtDefinition = gtProperties.get(propName);
6446 if (gtDefinition == null) {
6447 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND,
6448 propName, groupName, groupType));
6451 ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
6453 String convertedValue = null;
6454 if (value != null) {
6455 if (type == null || value instanceof Map || value instanceof List) {
6456 convertedValue = gson.toJson(value);
6458 convertedValue = value.toString();
6462 GroupProperty groupProperty = new GroupProperty();
6463 groupProperty.setValue(convertedValue);
6464 groupProperty.setName(propName);
6466 log.trace("After building group property {}", groupProperty);
6468 result.add(groupProperty);
6475 return Either.left(result);
6478 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
6482 Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID",
6484 if (userValidation.isRight()) {
6485 return Either.right(userValidation.right().value());
6489 // get resource from csar uuid
6490 Either<Resource, StorageOperationStatus> either = toscaOperationFacade
6491 .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
6492 if (either.isRight()) {
6493 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
6495 return Either.right(resp);
6498 return Either.left(either.left().value());
6502 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
6503 String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
6507 private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(
6508 String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
6509 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
6510 ResponseFormat responseFormat;
6511 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
6513 for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
6514 String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
6515 if (!defaultCapabilities.containsKey(capabilityType)) {
6516 responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
6518 return Either.right(responseFormat);
6520 CapabilityDefinition defaultCapability;
6521 if (CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
6522 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
6524 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
6525 .getToscaFullElement(resourceId);
6526 if (getFullComponentRes.isRight()) {
6527 log.debug("Failed to get full component {}. Status is {}. ", resourceId,
6528 getFullComponentRes.right().value());
6529 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
6531 return Either.right(responseFormat);
6533 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
6535 if (CollectionUtils.isEmpty(defaultCapability.getProperties())
6536 && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) {
6537 log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
6538 defaultCapability.getName(), resourceId);
6540 "Failed to update capability property values. Property list of fetched capability {} is empty. ",
6541 defaultCapability.getName());
6542 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
6543 return Either.right(responseFormat);
6545 if (CollectionUtils.isNotEmpty(defaultCapability.getProperties())
6546 && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) {
6547 Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(
6548 defaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
6549 if (validationRes.isRight()) {
6550 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
6551 validationRes.right().value());
6552 return Either.right(responseFormat);
6555 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
6556 validCapabilityList.add(defaultCapability);
6557 validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
6560 return Either.left(validCapabilitiesMap);
6563 private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(
6564 CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
6565 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
6566 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
6567 .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
6568 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
6569 for (UploadPropInfo property : uploadedProperties) {
6570 String propertyName = property.getName().toLowerCase();
6571 String propertyType = property.getType();
6572 ComponentInstanceProperty validProperty;
6573 if (defaultProperties.containsKey(propertyName)) {
6574 if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
6575 return Either.right(propertyName);
6578 validProperty = new ComponentInstanceProperty();
6579 validProperty.setName(propertyName);
6580 if (property.getValue() != null)
6581 validProperty.setValue(property.getValue().toString());
6582 validProperty.setDescription(property.getDescription());
6583 validProperty.setPassword(property.isPassword());
6584 validProperties.add(validProperty);
6586 defaultCapability.setProperties(validProperties);
6587 return Either.left(true);
6590 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
6591 List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
6592 Resource resource, User user) {
6594 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
6595 ArtifactOperationEnum.class);
6596 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
6597 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
6598 .left(nodeTypeArtifactsToHandle);
6601 // add all found Csar artifacts to list to upload
6602 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
6603 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
6604 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
6605 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
6606 ArtifactDefinition foundArtifact;
6608 if (!existingArtifactsToHandle.isEmpty()) {
6609 foundArtifact = existingArtifactsToHandle.stream()
6610 .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
6612 if (foundArtifact != null) {
6613 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
6614 .getArtifactType()) {
6615 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
6616 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
6617 // if current artifact already exists, but has
6618 // different content, add him to the list to
6620 artifactsToUpdate.add(currNewArtifact);
6622 // remove found artifact from the list of existing
6623 // artifacts to handle, because it was already
6625 existingArtifactsToHandle.remove(foundArtifact);
6626 // and remove found artifact from the list to
6627 // upload, because it should either be updated or be
6629 artifactsToUpload.remove(currNewArtifact);
6631 log.debug("Can't upload two artifact with the same name {}.",
6632 currNewArtifact.getArtifactName());
6633 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
6634 ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
6635 currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
6636 foundArtifact.getArtifactType());
6637 AuditingActionEnum auditingAction = artifactsBusinessLogic
6638 .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
6639 ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
6640 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
6641 user, null, null, foundArtifact.getUniqueId(), responseFormat,
6642 resource.getComponentType(), null);
6643 responseWrapper.setInnerElement(responseFormat);
6649 if (responseWrapper.isEmpty()) {
6650 for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
6651 if (currArtifact.getIsFromCsar()) {
6652 artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
6654 artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
6659 if (responseWrapper.isEmpty()) {
6660 if (!artifactsToUpload.isEmpty())
6661 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
6662 if (!artifactsToUpdate.isEmpty())
6663 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
6664 if (!artifactsToDelete.isEmpty())
6665 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
6667 if (!responseWrapper.isEmpty()) {
6668 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
6670 } catch (Exception e) {
6671 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
6672 responseWrapper.setInnerElement(responseFormat);
6673 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
6675 return nodeTypeArtifactsToHandleRes;
6678 private ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
6679 String nodeTypeFullName) {
6681 String actualVfName;
6682 if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
6683 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
6684 actualType = ResourceTypeEnum.VFC.name();
6686 actualVfName = vfResourceName;
6687 actualType = nodeResourceType;
6690 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
6691 String nameWithouNamespacePrefix = nodeTypeFullName
6692 .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
6693 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
6694 String resourceType = findTypes[0];
6695 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
6697 if (actualName.startsWith(Constants.ABSTRACT)) {
6698 toscaResourceName.append(resourceType.toLowerCase()).append('.')
6699 .append(ValidationUtils.convertToSystemName(actualVfName));
6701 toscaResourceName.append(actualType.toLowerCase()).append('.')
6702 .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
6704 StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
6705 return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
6706 previousToscaResourceName
6707 .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
6711 public ICacheMangerOperation getCacheManagerOperation() {
6712 return cacheManagerOperation;
6715 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
6716 this.cacheManagerOperation = cacheManagerOperation;
6719 ///////////////////////////////////////// DataModel
6720 ///////////////////////////////////////// refactoring/////////////////////////////////////////////
6722 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
6723 List<String> dataParamsToReturn) {
6725 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
6726 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
6729 if (resourceResultEither.isRight()) {
6730 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
6731 log.debug("Failed to found resource with id {} ", resourceId);
6732 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
6735 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
6736 return Either.right(componentsUtils.getResponseFormatByResource(
6737 componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
6740 Resource resource = resourceResultEither.left().value();
6741 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
6742 dataParamsToReturn);
6743 return Either.left(dataTransfer);
6747 public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
6748 Resource resource = (Resource) clonedComponent;
6749 if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
6750 Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
6751 .shouldUpgradeToLatestDerived(resource);
6752 if (shouldUpgradeToLatestDerived.isRight()) {
6753 return Either.right(
6754 componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
6756 return Either.left(shouldUpgradeToLatestDerived.left().value());
6758 return super.shouldUpgradeToLatestDerived(clonedComponent);