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;
23 import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH;
24 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
26 import java.nio.charset.StandardCharsets;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.EnumMap;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Optional;
39 import java.util.function.Function;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42 import java.util.stream.Collectors;
44 import javax.servlet.ServletContext;
46 import org.apache.commons.codec.binary.Base64;
47 import org.apache.commons.collections.MapUtils;
48 import org.apache.commons.lang3.tuple.ImmutablePair;
49 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
50 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
51 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
52 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
53 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
54 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
55 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
56 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
57 import org.openecomp.sdc.be.config.BeEcompErrorManager;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
59 import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
60 import org.openecomp.sdc.be.config.ConfigurationManager;
61 import org.openecomp.sdc.be.dao.api.ActionStatus;
62 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
63 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
64 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
65 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
66 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
67 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
69 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
70 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
71 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
72 import org.openecomp.sdc.be.impl.ComponentsUtils;
73 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
74 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
75 import org.openecomp.sdc.be.info.MergedArtifactInfo;
76 import org.openecomp.sdc.be.model.ArtifactDefinition;
77 import org.openecomp.sdc.be.model.CapabilityDefinition;
78 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
79 import org.openecomp.sdc.be.model.Component;
80 import org.openecomp.sdc.be.model.ComponentInstance;
81 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
82 import org.openecomp.sdc.be.model.ComponentParametersView;
83 import org.openecomp.sdc.be.model.DataTypeDefinition;
84 import org.openecomp.sdc.be.model.GroupDefinition;
85 import org.openecomp.sdc.be.model.GroupProperty;
86 import org.openecomp.sdc.be.model.GroupTypeDefinition;
87 import org.openecomp.sdc.be.model.HeatParameterDefinition;
88 import org.openecomp.sdc.be.model.InputDefinition;
89 import org.openecomp.sdc.be.model.InterfaceDefinition;
90 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
91 import org.openecomp.sdc.be.model.LifecycleStateEnum;
92 import org.openecomp.sdc.be.model.Operation;
93 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
94 import org.openecomp.sdc.be.model.PropertyDefinition;
95 import org.openecomp.sdc.be.model.RelationshipImpl;
96 import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
97 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
98 import org.openecomp.sdc.be.model.RequirementDefinition;
99 import org.openecomp.sdc.be.model.Resource;
100 import org.openecomp.sdc.be.model.UploadCapInfo;
101 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
102 import org.openecomp.sdc.be.model.UploadPropInfo;
103 import org.openecomp.sdc.be.model.UploadReqInfo;
104 import org.openecomp.sdc.be.model.UploadResourceInfo;
105 import org.openecomp.sdc.be.model.User;
106 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
107 import org.openecomp.sdc.be.model.category.CategoryDefinition;
108 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
109 import org.openecomp.sdc.be.model.heat.HeatParameterType;
110 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
111 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
112 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
113 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
114 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
115 import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
116 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
117 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
118 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
119 import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
120 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
121 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
122 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
123 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
124 import org.openecomp.sdc.be.servlets.RepresentationUtils;
125 import org.openecomp.sdc.be.tosca.CsarUtils;
126 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
127 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
128 import org.openecomp.sdc.be.user.IUserBusinessLogic;
129 import org.openecomp.sdc.be.user.Role;
130 import org.openecomp.sdc.be.user.UserBusinessLogic;
131 import org.openecomp.sdc.be.utils.CommonBeUtils;
132 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
133 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
134 import org.openecomp.sdc.common.api.Constants;
135 import org.openecomp.sdc.common.config.EcompErrorName;
136 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
137 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
138 import org.openecomp.sdc.common.datastructure.Wrapper;
139 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
140 import org.openecomp.sdc.common.util.GeneralUtility;
141 import org.openecomp.sdc.common.util.ValidationUtils;
142 import org.openecomp.sdc.exception.ResponseFormat;
143 import org.slf4j.Logger;
144 import org.slf4j.LoggerFactory;
145 import org.springframework.beans.factory.annotation.Autowired;
146 import org.springframework.web.context.WebApplicationContext;
147 import org.yaml.snakeyaml.DumperOptions;
148 import org.yaml.snakeyaml.Yaml;
150 import com.google.gson.Gson;
151 import com.google.gson.JsonElement;
152 import com.google.gson.JsonObject;
154 import fj.data.Either;
156 @org.springframework.stereotype.Component("resourceBusinessLogic")
157 public class ResourceBusinessLogic extends ComponentBusinessLogic {
159 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
160 public static final String INITIAL_VERSION = "0.1";
162 private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
163 private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
164 private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
165 private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
167 private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName());
169 private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
172 * Default constructor
174 public ResourceBusinessLogic() {
175 log.debug("ResourceBusinessLogic started");
179 private ICapabilityTypeOperation capabilityTypeOperation = null;
182 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
185 private LifecycleBusinessLogic lifecycleBusinessLogic;
188 private IPropertyOperation propertyOperation;
191 private CsarOperation csarOperation;
194 private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic;
197 private ResourceImportManager resourceImportManager;
200 private GroupBusinessLogic groupBusinessLogic;
203 private InputsBusinessLogic inputsBusinessLogic;
205 @javax.annotation.Resource
206 private InputsOperation inputOperation;
209 // private GroupOperation groupOperation;
212 private IHeatParametersOperation heatParametersOperation;
215 // private IArtifactOperation artifactOperation;
218 private CompositionBusinessLogic compositionBusinessLogic;
221 private ICacheMangerOperation cacheManagerOperation;
224 private ApplicationDataTypeCache dataTypeCache;
226 private Gson gson = new Gson();
228 public CsarOperation getCsarOperation() {
229 return csarOperation;
232 public void setCsarOperation(CsarOperation csarOperation) {
233 this.csarOperation = csarOperation;
236 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
237 return lifecycleBusinessLogic;
240 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
241 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
244 public IElementOperation getElementDao() {
248 public void setElementDao(IElementOperation elementDao) {
249 this.elementDao = elementDao;
252 public IUserBusinessLogic getUserAdmin() {
253 return this.userAdmin;
256 public void setUserAdmin(UserBusinessLogic userAdmin) {
257 this.userAdmin = userAdmin;
260 public ComponentsUtils getComponentsUtils() {
261 return this.componentsUtils;
264 public void setComponentsUtils(ComponentsUtils componentsUtils) {
265 this.componentsUtils = componentsUtils;
268 public ArtifactsBusinessLogic getArtifactsManager() {
269 return artifactsBusinessLogic;
272 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
273 this.artifactsBusinessLogic = artifactsManager;
276 public void setPropertyOperation(IPropertyOperation propertyOperation) {
277 this.propertyOperation = propertyOperation;
280 public ApplicationDataTypeCache getApplicationDataTypeCache() {
281 return applicationDataTypeCache;
284 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
285 this.applicationDataTypeCache = applicationDataTypeCache;
289 * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param
296 public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
297 Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
298 if (resp.isRight()) {
299 return Either.right(resp.right().value());
301 Boolean isHighest = null;
302 switch (highestFilter) {
308 case NON_HIGHEST_ONLY:
314 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
316 if (getResponse.isRight()) {
317 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
320 return Either.left(getResponse.left().value());
323 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) {
325 Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
326 if (resp.isRight()) {
327 return Either.right(resp.right().value());
330 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
334 if (dataModelResponse.isLeft()) {
335 Map<String, Boolean> result = new HashMap<>();
336 result.put("isValid", dataModelResponse.left().value());
337 log.debug("validation was successfully performed.");
338 return Either.left(result);
341 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
343 return Either.right(responseFormat);
346 public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
347 Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
348 if (createResourceResponse.isRight()) {
349 return createResourceResponse;
352 // Creating resource either by DAO or from CSAR
353 String csarUUID = null;
354 if (payloadName == null) {
355 csarUUID = resource.getCsarUUID();
357 csarUUID = payloadName;
359 if (csarUUID != null && !csarUUID.isEmpty()) {
360 // check if VF with the same Csar UUID or with he same name already
362 Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
363 if (validateCsarUuidUniquenessRes.isRight()) {
364 log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
365 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
368 Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
369 if (existingResourceRes.intValue() > 0) {
370 log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
371 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID);
372 componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null);
373 return Either.right(errorResponse);
376 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
377 createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
378 return createResourceResponse;
381 return createResourceByDao(resource, user, auditingAction, false, false, null);
384 public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
385 Either<Resource, ResponseFormat> updateResourceResponse = null;
386 Either<Resource, ResponseFormat> validateResourceResponse = null;
387 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
388 String csarUUID = null;
389 String csarVersion = null;
390 if (payloadName == null) {
391 csarUUID = resource.getCsarUUID();
392 csarVersion = resource.getCsarVersion();
394 csarUUID = payloadName;
396 if (csarUUID != null && !csarUUID.isEmpty()) {
397 Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
398 if (responseWrapper.isEmpty()) {
399 validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
401 if (responseWrapper.isEmpty()) {
402 validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
404 if (responseWrapper.isEmpty()) {
405 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
406 overrideImmutableMetadata(oldResource, resource);
408 validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
409 if (validateResourceResponse.isRight()) {
410 responseWrapper.setInnerElement(validateResourceResponse.right().value());
413 if (responseWrapper.isEmpty()) {
414 String oldCsarVersion = oldResource.getCsarVersion();
415 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId);
416 // (on boarding flow): If the update includes same csarUUID and
417 // same csarVersion as already in the VF - no need to import the
418 // csar (do only metadata changes if there are).
419 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
420 updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
422 updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
426 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
427 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName());
428 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
429 responseWrapper.setInnerElement(errorResponse);
431 if (responseWrapper.isEmpty()) {
432 return updateResourceResponse;
434 return Either.right(responseWrapper.getInnerElement());
437 private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource, Resource resource, String csarUUID, User user) {
438 // (on boarding flow): If the update includes a csarUUID: verify this
439 // csarUUID is not in use by another VF, If it is - use same error as
441 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
442 // select another or update the existing VF." %1 - csarUUID, %2 - VF
444 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade.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, resource.getSystemName());
448 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
450 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
451 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
452 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
453 responseWrapper.setInnerElement(errorResponse);
457 private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
458 // (on boarding flow): If the update includes csarUUID which is
459 // different from the csarUUID of the VF - fail with
460 // error: "Error: Resource %1 cannot be updated using since it is linked
461 // to a different VSP" %1 - VF name
462 String oldCsarUUID = oldResource.getCsarUUID();
463 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
464 log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", resourceUniqueId, csarUUID, oldCsarUUID);
465 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
466 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
467 responseWrapper.setInnerElement(errorResponse);
471 private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
472 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId);
473 if (oldResourceRes.isRight()) {
474 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
475 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
478 return oldResourceRes.left().value();
481 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
482 resource.setName(oldRresource.getName());
483 resource.setIcon(oldRresource.getIcon());
484 resource.setTags(oldRresource.getTags());
485 resource.setVendorName(oldRresource.getVendorName());
486 resource.setCategories(oldRresource.getCategories());
487 resource.setDerivedFrom(oldRresource.getDerivedFrom());
490 private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload,
494 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
495 if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
496 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", oldRresource.getLastUpdaterUserId(), user.getUserId());
497 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
500 String lockedResourceId = oldRresource.getUniqueId();
501 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
502 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
504 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
505 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
506 csar = csarUIPayload;
508 csar = csarOperation.getCsar(csarUUID, user);
510 if (csar.isRight()) {
511 log.debug("Failed to get csar for casrUUID{} ", csarUUID);
512 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
515 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, user, csarUUID, csar);
516 if (toscaYamlCsarStatus.isRight()) {
517 return Either.right(toscaYamlCsarStatus.right().value());
519 Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
520 if (checksum.isRight()) {
521 log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
522 return Either.right(checksum.right().value());
524 boolean isUpdateYaml = true;
525 if (checksum.left().value().equals(oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
526 log.debug("The checksums are equals for csarUUID {}, existing checsum is {}, new one is {} ", csarUUID, oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum.left().value());
527 if (oldRresource.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT))
528 isUpdateYaml = false;
530 oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum.left().value());
533 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource, "update Resource From Csar");
534 if (lockResult.isRight()) {
535 return Either.right(lockResult.right().value());
538 Either<Resource, ResponseFormat> result = null;
539 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
540 Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = null;
542 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate = null;
543 Resource preparedResource = null;
544 Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user);
545 if (uploadComponentInstanceInfoMap.isRight()) {
546 ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
547 componentsUtils.auditResource(responseFormat, user, newRresource, "", "", updateResource, null);
548 result = Either.right(responseFormat);
551 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances();
552 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true, instances);
553 if (findNodeTypesArtifactsToHandleRes.isRight()) {
554 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID);
555 result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
558 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value();
559 if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) {
561 prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, user, true, false);
562 if (prepareForUpdate.isRight()) {
563 log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
564 result = Either.right(prepareForUpdate.right().value());
567 preparedResource = prepareForUpdate.left().value().left;
569 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
570 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
572 parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
573 if (parseNodeTypeInfoYamlEither.isRight()) {
574 ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
575 componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null);
576 result = Either.right(responseFormat);
580 Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
581 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource, user, inputs, true);
582 if (createInputsOnResource.isRight()) {
583 log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
584 ResponseFormat responseFormat = createInputsOnResource.right().value();
585 componentsUtils.auditResource(createInputsOnResource.right().value(), user, preparedResource, "", "", updateResource, null);
586 result = Either.right(responseFormat);
589 preparedResource = createInputsOnResource.left().value();
591 Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(user, yamlFileName, preparedResource, instances, true, false, parseNodeTypeInfoYamlEither.left().value());
592 if (createResourcesInstancesEither.isRight()) {
593 log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
594 ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
595 componentsUtils.auditResource(createResourcesInstancesEither.right().value(), user, preparedResource, "", "", updateResource, null);
596 result = Either.right(responseFormat);
599 preparedResource = createResourcesInstancesEither.left().value();
601 createResourcesInstancesEither = createResourceInstancesRelations(user, yamlFileName, preparedResource, instances, true, false);
602 if (createResourcesInstancesEither.isRight()) {
603 log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
604 result = Either.right(createResourcesInstancesEither.right().value());
608 preparedResource = createResourcesInstancesEither.left().value();
610 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), preparedResource.getSystemName());
611 if (validateUpdateVfGroupNamesRes.isRight()) {
613 return Either.right(validateUpdateVfGroupNamesRes.right().value());
615 // add groups to resource
616 Map<String, GroupDefinition> groups;
618 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
619 groups = validateUpdateVfGroupNamesRes.left().value();
621 groups = uploadComponentInstanceInfoMap.left().value().getGroups();
623 Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource, user, groups);
624 if (updatedGroupsOnResource.isRight()) {
626 return updatedGroupsOnResource;
628 preparedResource = updatedGroupsOnResource.left().value();
631 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(oldRresource.getUniqueId(), newRresource, user, oldRresource, false, true);
632 if (dataModelResponse.isRight()) {
633 log.debug("failed to update resource metadata {}", dataModelResponse.right().value());
634 result = Either.right(dataModelResponse.right().value());
637 preparedResource = dataModelResponse.left().value();
640 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts,
641 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), false, true);
642 if (createdCsarArtifactsEither.isRight()) {
644 return createdCsarArtifactsEither;
646 preparedResource = createdCsarArtifactsEither.left().value();
648 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, user.getUserId());
649 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource);
654 if (result == null || result.isRight()) {
655 log.warn("operation failed. do rollback");
657 if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
658 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
659 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
660 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
661 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
662 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, oldRresource.getName());
664 log.debug("component and all its artifacts were deleted, id = {}", oldRresource.getName());
667 log.debug("operation success. do commit");
670 log.debug("unlock resource {}", lockedResourceId);
671 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
676 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, byte[]> csar, String csarUUID, String yamlFileName, Resource oldResource, User user,
677 boolean inTransaction, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
679 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
680 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
681 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
684 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
685 List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap);
686 validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
687 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null;
688 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
689 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarUUID);
691 for (ImmutablePair<ImmutablePair<String, List<String>>, String> currVfcToscaNameEntry : extractedVfcToscaNames) {
692 String currVfcToscaName = currVfcToscaNameEntry.getValue();
693 log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
695 Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
696 Resource curNodeType = null;
697 if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
698 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value());
699 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarUUID);
700 componentsUtils.auditResource(responseFormat, user, oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
701 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
703 } else if (curVfcRes.isLeft()) {
704 curNodeType = curVfcRes.left().value();
706 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
707 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
708 for (String currNamespace : currVfcToscaNameEntry.getKey().getValue()) {
709 if (extractedVfcsArtifacts.containsKey(currNamespace)) {
710 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
713 curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
714 if (curNodeTypeArtifactsToHandleRes.isRight()) {
715 nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
718 curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
720 } else if (curNodeType != null) {
721 // delete all artifacts if have not received artifacts from csar
722 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
723 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
724 // delete all informational artifacts
725 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList()));
726 // delete all deployment artifacts
727 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
728 if (!artifactsToDelete.isEmpty()) {
729 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
732 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
733 nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey().getKey(), curNodeTypeArtifactsToHandle);
736 } catch (Exception e) {
737 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
738 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
739 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
741 return nodeTypesArtifactsToHandleRes;
744 private void validateNodeTypeIdentifiers(Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames) {
745 if (extractedVfcsArtifacts != null) {
746 List<String> validIdentifiers = new ArrayList<>();
747 if (extractedVfcToscaNames != null) {
748 extractedVfcToscaNames.stream().forEach(pair -> {
749 validIdentifiers.addAll(pair.getKey().getValue());
750 validIdentifiers.add(pair.getKey().getKey());
753 for (String curIdentifier : extractedVfcsArtifacts.keySet()) {
754 if (validIdentifiers != null && !validIdentifiers.contains(curIdentifier))
755 log.warn("Warning - VFC identification {} provided in the Artifacts folder of the CSAR is not valid. ", curIdentifier);
760 private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
762 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
763 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
764 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
766 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
767 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
768 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
769 if (curNodeType != null) {
770 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
771 if (curNodeType.getDeploymentArtifacts() != null) {
772 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
774 if (curNodeType.getArtifacts() != null) {
775 existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
777 for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
778 ArtifactDefinition foundArtifact;
780 if (!existingArtifacts.isEmpty()) {
781 foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
782 if (foundArtifact != null) {
783 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
784 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
785 foundArtifact.setPayload(currNewArtifact.getPayloadData());
786 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
787 foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(currNewArtifact.getPayloadData()));
788 artifactsToUpdate.add(foundArtifact);
790 existingArtifacts.remove(foundArtifact.getArtifactLabel());
791 artifactsToUpload.remove(currNewArtifact);
793 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
794 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
795 foundArtifact.getArtifactType());
796 responseWrapper.setInnerElement(responseFormat);
802 if (responseWrapper.isEmpty()) {
803 artifactsToDelete.addAll(existingArtifacts.values());
806 if (responseWrapper.isEmpty()) {
807 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
808 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
809 if (!artifactsToUpload.isEmpty())
810 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
811 if (!artifactsToUpdate.isEmpty())
812 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
813 if (!artifactsToDelete.isEmpty())
814 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
816 nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
818 if (!responseWrapper.isEmpty()) {
819 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
821 } catch (Exception e) {
822 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
823 responseWrapper.setInnerElement(responseFormat);
824 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
826 return nodeTypeArtifactsToHandleRes;
830 * Changes resource life cycle state to checked out
834 * @param inTransaction
837 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
838 Either<Resource, ResponseFormat> checkoutResourceRes;
840 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
841 log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
842 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
843 new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
844 if (checkoutRes.isRight()) {
845 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
846 checkoutResourceRes = Either.right(checkoutRes.right().value());
848 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
851 checkoutResourceRes = Either.left(resource);
853 } catch (Exception e) {
854 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
855 checkoutResourceRes = Either.right(responseFormat);
856 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
858 return checkoutResourceRes;
862 * Handles Artifacts of NodeType
864 * @param nodeTypeResource
865 * @param nodeTypeArtifactsToHandle
866 * @param vfcsNewCreatedArtifacts
868 * @param inTransaction
871 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
872 User user, boolean inTransaction) {
873 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
874 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
875 Either<Resource, ResponseFormat> changeStateResponse;
877 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
878 if (changeStateResponse.isRight()) {
879 return Either.right(changeStateResponse.right().value());
881 nodeTypeResource = changeStateResponse.left().value();
883 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
884 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
885 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
886 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
887 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
888 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
889 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
890 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, vfcsNewCreatedArtifacts,
891 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, curOperation), false, inTransaction);
892 if (handleNodeTypeArtifactsRequestRes.isRight()) {
893 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
896 if (curOperation == ArtifactOperationEnum.Create) {
897 vfcsNewCreatedArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
899 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
902 if (handleNodeTypeArtifactsRes == null) {
903 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
905 } catch (Exception e) {
906 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
907 handleNodeTypeArtifactsRes = Either.right(responseFormat);
908 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
910 return handleNodeTypeArtifactsRes;
913 @SuppressWarnings("unchecked")
914 private List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractVfcToscaNames(Map<String, byte[]> csar, String yamlFileName, String vfResourceName, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
915 List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames = new ArrayList<>();
916 Map<String, Object> nodeTypes;
918 nodeTypes = new HashMap<>();
919 putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
920 putNodeTypesFromYaml(csar, Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE, nodeTypes);
921 putNodeTypesFromYaml(csar, Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE, nodeTypes);
922 Map<String,String> nestedServiceTemplatesMap = new HashMap<>();
923 for(UploadComponentInstanceInfo ci : uploadComponentInstanceInfoMap.values()){
924 if(ci.getProperties() != null && ci.getProperties().containsKey("service_template_filter")){
925 String tempName = CsarUtils.DEFINITIONS_PATH + ((Map<String, String>)ci.getProperties().get("service_template_filter").get(0).getValue()).get("substitute_service_template");
926 putNodeTypesFromYaml(csar,tempName, nodeTypes);
927 nestedServiceTemplatesMap.put(ci.getType(), tempName);
931 if (!nodeTypes.isEmpty()) {
932 Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
933 while (nodesNameEntry.hasNext()) {
934 Entry<String, Object> nodeType = nodesNameEntry.next();
935 addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey(), nestedServiceTemplatesMap);
939 return vfcToscaNames;
942 @SuppressWarnings("unchecked")
943 private void putNodeTypesFromYaml(Map<String, byte[]> csar, String yamlFileName, Map<String, Object> nodeTypes) {
945 if (csar.containsKey(yamlFileName)) {
946 Map<String, Object> mappedToscaTemplate;
947 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes;
948 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(new String(csar.get(yamlFileName), StandardCharsets.UTF_8));
949 eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
950 if (eitherNodeTypes.isLeft()) {
951 nodeTypes.putAll(eitherNodeTypes.left().value());
956 private void addVfcToscaNameFindSubstitutes(Map<String, byte[]> csar, String vfResourceName, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames, String nodeTypeFullName, Map<String, String> nestedServiceTemplatesMap) {
958 String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName);
959 String nodeTypeTemplateYamlName =null;
960 if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){
961 nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName);
963 List<String> relatedVfcsToscaNameSpaces = new ArrayList<>();
964 relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName));
965 if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) {
966 addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces, nestedServiceTemplatesMap);
968 ImmutablePair<String, List<String>> toscaNameSpacesHierarchy = new ImmutablePair<>(nodeTypeFullName, relatedVfcsToscaNameSpaces);
969 vfcToscaNames.add(new ImmutablePair<>(toscaNameSpacesHierarchy, toscaResourceName));
972 private void addSubstituteToscaNamespacesRecursively(Map<String, byte[]> csar, String yamlFileName, List<String> toscaNameSpaces, Map<String, String> nestedServiceTemplatesMap) {
974 Map<String, Object> nodeTypes = new HashMap<>();
976 if (csar.containsKey(yamlFileName)) {
977 putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
979 if (!nodeTypes.isEmpty()) {
980 Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
981 while (nodesNameEntry.hasNext()) {
982 Entry<String, Object> nodeType = nodesNameEntry.next();
983 String nodeTypeFullName = nodeType.getKey();
984 String toscaNameSpace = buildNestedVfcToscaNamespace(nodeTypeFullName);
985 if (toscaNameSpaces.contains(toscaNameSpace)) {
988 toscaNameSpaces.add(toscaNameSpace);
990 String nodeTypeTemplateYamlName =null;
991 if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){
992 nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName);
995 if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) {
996 addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces, nestedServiceTemplatesMap);
1002 public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
1003 log.trace("************* created successfully from YAML, resource TOSCA ");
1005 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
1006 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
1007 csar = csarUIPayload;
1009 csar = csarOperation.getCsar(csarUUID, user);
1012 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar);
1013 if (toscaYamlCsarStatus.isRight()) {
1014 return Either.right(toscaYamlCsarStatus.right().value());
1016 Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
1017 if (toscaYamlChecksum.isRight()) {
1018 log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, toscaYamlChecksum.right().value());
1019 return Either.right(toscaYamlChecksum.right().value());
1021 resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value());
1023 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
1024 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
1025 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
1026 Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, user, yamlFileContents, yamlFileName, csar.left().value(), csarUUID);
1027 if (createResourceFromYaml.isRight()) {
1028 log.debug("Couldn't create resource from YAML");
1029 return Either.right(createResourceFromYaml.right().value());
1032 Resource vfResource = createResourceFromYaml.left().value();
1033 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
1034 return Either.left(vfResource);
1037 private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
1038 if (csar.isRight()) {
1039 StorageOperationStatus value = csar.right().value();
1040 log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
1041 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1042 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
1043 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1044 return Either.right(responseFormat);
1047 Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils);
1048 if (validateCsarStatus.isRight()) {
1049 ResponseFormat responseFormat = validateCsarStatus.right().value();
1050 log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
1051 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1052 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1053 return Either.right(responseFormat);
1056 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
1058 if (toscaYamlCsarStatus.isRight()) {
1059 ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
1060 log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
1061 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1062 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1063 return Either.right(responseFormat);
1065 return toscaYamlCsarStatus;
1068 private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1069 log.trace("validating resource before create");
1070 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false);
1071 if (eitherCreator.isRight()) {
1072 return Either.right(eitherCreator.right().value());
1074 user.copyData(eitherCreator.left().value());
1076 // validate user role
1077 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
1078 if (validateRes.isRight()) {
1079 return Either.right(validateRes.right().value());
1081 // VF "derivedFrom" should be null (or ignored)
1082 if (!resource.getResourceType().equals(ResourceTypeEnum.VF)) {
1083 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1084 if (validateDerivedFromNotEmpty.isRight()) {
1085 return Either.right(validateDerivedFromNotEmpty.right().value());
1088 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction);
1092 public Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, User user, String topologyTemplateYaml, String yamlName, Map<String, byte[]> csar, String csarUUID) {
1094 List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
1095 log.trace("************* createResourceFromYaml before parse yaml ");
1096 Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, user);
1097 if (parseResourceInfoFromYamlEither.isRight()) {
1098 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
1099 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1100 return Either.right(responseFormat);
1102 log.trace("************* createResourceFromYaml after parse yaml ");
1103 ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
1104 log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
1105 log.trace("************* createResourceFromYaml before create ");
1106 Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, user, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, csarUUID, csar, createdArtifacts, topologyTemplateYaml);
1107 log.trace("************* createResourceFromYaml after create ");
1108 if (createdResourceResponse.isRight()) {
1109 ResponseFormat responseFormat = createdResourceResponse.right().value();
1110 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1111 return Either.right(responseFormat);
1114 return createdResourceResponse;
1118 public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock,
1119 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1121 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
1123 Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
1124 if (tosca_version.isRight()) {
1125 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
1126 return Either.right(responseFormat);
1129 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
1131 Map<String, Resource> nodeTypesResources = new HashMap<>();
1132 Either<Map<String, Resource>, ResponseFormat> result = Either.left(nodeTypesResources);
1134 Map<String, Object> mapToConvert = new HashMap<String, Object>();
1135 mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
1137 if (eitherNodeTypes.isLeft()) {
1139 Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
1141 while (nodesNameValue.hasNext()) {
1143 Entry<String, Object> nodeType = nodesNameValue.next();
1144 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1145 log.trace("************* Going to create node {}", nodeType.getKey());
1146 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
1147 log.trace("************* finished to create node {}", nodeType.getKey());
1148 if (resourceCreated.isRight()) {
1149 return Either.right(resourceCreated.right().value());
1151 Resource vfcCreated = resourceCreated.left().value().getLeft();
1153 nodeTypesResources.put(nodeType.getKey(), vfcCreated);
1154 mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
1162 private String getNodeTypeActualName(String fullName) {
1163 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1164 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1165 String resourceType = findTypes[0];
1166 return nameWithouNamespacePrefix.substring(resourceType.length());
1169 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
1170 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1172 Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1173 if (resourceMetaData.isRight()) {
1174 return Either.right(resourceMetaData.right().value());
1177 // We need to create a Yaml from each node_types in order to create
1178 // resource from each node type using import normative flow.
1179 DumperOptions options = new DumperOptions();
1180 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1181 Yaml yaml = new Yaml(options);
1183 Map<String, Object> singleVfc = new HashMap<>();
1185 String actualName = this.getNodeTypeActualName(nodeNameValue.getKey());
1186 if (!actualName.startsWith(Constants.ABSTRACT)) {
1187 actualName = "." + Constants.ABSTRACT + actualName;
1190 // Setting tosca name
1191 String toscaResourceName = ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + resourceMetaData.left().value().getResourceType().toLowerCase() + '.' + resourceVf.getSystemName() + actualName;
1192 singleVfc.put(toscaResourceName, nodeNameValue.getValue());
1193 mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), singleVfc);
1195 String singleVfcYaml = yaml.dumpAsMap(mapToConvert);
1197 Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1198 if (eitherCreator.isRight()) {
1199 return Either.right(eitherCreator.right().value());
1201 user = eitherCreator.left().value();
1203 return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
1206 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1208 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1209 if (validateDerivedFromNotEmpty.isRight()) {
1210 return Either.right(validateDerivedFromNotEmpty.right().value());
1212 return Either.left(true);
1215 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1216 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1218 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1219 Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
1220 return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
1223 private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeTypeName, User user) {
1224 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1226 // validate nodetype name prefix
1227 if (!nodeTypeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1228 log.debug("invalid nodeTypeName:{} does not start with {}.", nodeTypeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1229 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeTypeName);
1230 return Either.right(responseFormat);
1233 String actualName = this.getNodeTypeActualName(nodeTypeName);
1234 String namePrefix = nodeTypeName.replace(actualName, "");
1235 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1237 // if we import from csar, the node_type name can be
1238 // org.openecomp.resource.abstract.node_name - in this case we always
1240 if (resourceType.equals(Constants.ABSTRACT)) {
1241 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1244 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1245 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1246 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeTypeName);
1247 return Either.right(responseFormat);
1251 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1253 // Setting type from name
1254 String type = resourceType.toUpperCase();
1255 resourceMetaData.setResourceType(type);
1257 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1258 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1259 resourceMetaData.setContactId(user.getUserId());
1260 resourceMetaData.setVendorName(resourceVf.getVendorName());
1261 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1264 List<String> tags = new ArrayList<>();
1265 tags.add(resourceMetaData.getName());
1266 resourceMetaData.setTags(tags);
1269 CategoryDefinition category = new CategoryDefinition();
1270 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1271 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1272 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1273 category.addSubCategory(subCategory);
1274 List<CategoryDefinition> categories = new ArrayList<>();
1275 categories.add(category);
1276 resourceMetaData.setCategories(categories);
1278 return Either.left(resourceMetaData);
1281 private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, User user, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, String csarUUID,
1282 Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml) {
1284 boolean result = true;
1285 boolean inTransaction = true;
1286 Map<String, Resource> createdVfcs = new HashMap<>();
1287 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1288 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
1289 if (lockResult.isRight()) {
1290 ResponseFormat responseFormat = lockResult.right().value();
1291 return Either.right(responseFormat);
1293 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1296 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1297 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
1298 if (genericResourceEither.isRight()) {
1300 return genericResourceEither;
1302 Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, user, isNormative, inTransaction);
1303 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1304 if (createResourcesEither.isRight()) {
1306 return createResourcesEither;
1308 resource = createResourcesEither.left().value();
1309 // add groups to resource
1310 log.trace("************* Going to add inputs from yaml {}", yamlName);
1311 if (resource.shouldGenerateInputs())
1312 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
1314 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1315 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, user, inputs, inTransaction);
1316 if (createInputsOnResource.isRight()) {
1318 return createInputsOnResource;
1320 resource = createInputsOnResource.left().value();
1321 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1323 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
1324 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1325 createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID, nodeTypesNewCreatedArtifacts, createdVfcs);
1326 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1327 if (createResourcesEither.isRight()) {
1329 return createResourcesEither;
1332 resource = createResourcesEither.left().value();
1333 // validate update vf module group names
1334 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1335 if (validateUpdateVfGroupNamesRes.isRight()) {
1337 return Either.right(validateUpdateVfGroupNamesRes.right().value());
1339 // add groups to resource
1340 Map<String, GroupDefinition> groups;
1341 log.trace("************* Going to add groups from yaml {}", yamlName);
1343 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1344 groups = validateUpdateVfGroupNamesRes.left().value();
1346 groups = parsedToscaYamlInfo.getGroups();
1348 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, user, groups);
1349 if (createGroupsOnResource.isRight()) {
1351 return createGroupsOnResource;
1353 resource = createGroupsOnResource.left().value();
1354 log.trace("************* Finished to add groups from yaml {}", yamlName);
1356 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1357 Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
1359 log.trace("************* Finished to add artifacts from yaml {}", yamlName);
1360 if (createdCsarArtifactsEither.isRight()) {
1362 return createdCsarArtifactsEither;
1365 resource = createdCsarArtifactsEither.left().value();
1366 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1367 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
1368 ASDCKpiApi.countCreatedResourcesKPI();
1369 return Either.left(resource);
1373 log.warn("operation failed. do rollback");
1374 titanDao.rollback();
1375 if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
1376 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1377 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
1378 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
1379 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
1380 ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, resource.getName());
1382 log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
1386 log.debug("operation success. do commit");
1390 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
1396 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1397 if (groups != null && !groups.isEmpty()) {
1398 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1400 if (mergeGroupsUsingResource.isRight()) {
1401 log.debug("Failed to prepare groups for creation");
1402 return Either.right(mergeGroupsUsingResource.right().value());
1404 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1405 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList);
1406 if (createGroups.isRight()) {
1407 return Either.right(createGroups.right().value());
1410 return Either.left(resource);
1412 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1413 if (updatedResource.isRight()) {
1414 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1415 return Either.right(responseFormat);
1417 return Either.left(updatedResource.left().value());
1420 private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1421 if (groups != null && false == groups.isEmpty()) {
1422 List<GroupDefinition> groupsFromResource = resource.getGroups();
1423 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1425 if (mergeGroupsUsingResource.isRight()) {
1426 log.debug("Failed to prepare groups for creation");
1427 return Either.right(mergeGroupsUsingResource.right().value());
1429 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1430 List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
1431 List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
1432 List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
1433 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1434 for (GroupDefinition group : groupsAsList) {
1435 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getName().equals(group.getName())).findAny();
1436 if (op.isPresent()) {
1437 GroupDefinition groupToUpdate = op.get();
1438 groupToUpdate.setMembers(group.getMembers());
1439 groupsToUpdate.add(groupToUpdate);
1441 groupsToCreate.add(group);
1444 for (GroupDefinition group : groupsFromResource) {
1445 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equals(group.getName())).findAny();
1446 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1448 groupsToDelete.add(group);
1453 groupsToCreate.addAll(groupsAsList);
1454 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
1455 if (!groupsToCreate.isEmpty()) {
1457 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1458 prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1460 prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1463 if (prepareGroups.isRight()) {
1464 return Either.right(prepareGroups.right().value());
1468 if (!groupsToDelete.isEmpty()) {
1469 prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
1470 if (prepareGroups.isRight()) {
1471 return Either.right(prepareGroups.right().value());
1475 if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
1476 prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
1477 if (prepareGroups.isRight()) {
1478 return Either.right(prepareGroups.right().value());
1483 return Either.left(resource);
1486 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1487 if (updatedResource.isRight()) {
1488 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1489 return Either.right(responseFormat);
1491 return Either.left(updatedResource.left().value());
1494 private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
1495 if (inputs != null && false == inputs.isEmpty()) {
1497 Either<List<InputDefinition>, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
1498 if (createGroups.isRight()) {
1499 return Either.right(createGroups.right().value());
1502 return Either.left(resource);
1505 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1506 if (updatedResource.isRight()) {
1507 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1508 return Either.right(responseFormat);
1510 return Either.left(updatedResource.left().value());
1513 private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1515 List<GroupDefinition> result = new ArrayList<>();
1517 List<ComponentInstance> componentInstances = component.getComponentInstances();
1519 if (groups != null) {
1520 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1521 if (validateCyclicGroupsDependencies.isRight()) {
1522 return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
1524 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1525 String groupName = entry.getKey();
1527 GroupDefinition groupDefinition = entry.getValue();
1529 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1530 updatedGroupDefinition.setMembers(null);
1532 // get the members of the group
1533 Map<String, String> members = groupDefinition.getMembers();
1534 if (members != null) {
1535 Set<String> compInstancesNames = members.keySet();
1537 if (componentInstances == null || true == componentInstances.isEmpty()) {
1538 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1539 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName());
1540 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1542 // Find all component instances with the member names
1543 Map<String, String> memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1544 memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
1545 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
1547 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1549 List<String> foundMembers = new ArrayList<>();
1550 if (relevantInstances != null) {
1551 foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
1553 compInstancesNames.removeAll(foundMembers);
1554 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1555 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1556 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1559 updatedGroupDefinition.setMembers(relevantInstances);
1562 result.add(updatedGroupDefinition);
1565 return Either.left(result);
1569 * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
1574 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1576 Either<Boolean, ResponseFormat> result = Either.left(true);
1578 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1579 while (allGroupsItr.hasNext() && result.isLeft()) {
1580 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1581 // Fetches a group member A
1582 String groupAName = groupAEntry.getKey();
1583 // Finds all group members in group A
1584 Set<String> allGroupAMembersNames = new HashSet<>();
1585 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1586 // If A is a group member of itself found cyclic dependency
1587 if (allGroupAMembersNames.contains(groupAName)) {
1588 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1589 result = Either.right(responseFormat);
1592 } catch (Exception e) {
1593 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1594 result = Either.right(responseFormat);
1595 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1601 * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
1605 * @param allGroupMembers
1608 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1610 // Found Cyclic dependency
1611 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1614 GroupDefinition groupDefinition = allGroups.get(groupName);
1615 // All Members Of Current Group Resource Instances & Other Groups
1616 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1617 // Filtered Members Of Current Group containing only members which
1619 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1620 // Keep Only Elements of type group and not Resource Instances
1621 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1622 // Add Filtered Elements to main Set
1623 peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
1625 collect(Collectors.toList());
1627 // Recursively call the method for all the filtered group members
1628 for (String innerGroupName : currGroupFilteredMembers) {
1629 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1634 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1636 boolean stop = false;
1637 // In Case Not Group Stop
1638 if (!allGroups.containsKey(groupName)) {
1641 // In Case Group Has no members stop
1643 GroupDefinition groupDefinition = allGroups.get(groupName);
1644 stop = MapUtils.isEmpty(groupDefinition.getMembers());
1647 // In Case all group members already contained stop
1649 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1650 Set<String> membersOfTypeGroup = allMembers.stream().
1651 // Filter In Only Group members
1652 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1654 collect(Collectors.toSet());
1655 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1660 private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, User user, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
1661 String topologyTemplateYaml, Map<String, byte[]> csar, String csarUUID, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs) {
1663 Either<Resource, ResponseFormat> result;
1664 Either<Resource, ResponseFormat> createResourcesInstancesEither;
1666 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource, uploadComponentInstanceInfoMap);
1668 log.debug("************* Going to create all nodes {}", yamlName);
1669 Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts);
1670 log.debug("************* Finished to create all nodes {}", yamlName);
1671 if (createdResourcesFromdNodeTypeMap.isRight()) {
1672 log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
1673 return Either.right(createdResourcesFromdNodeTypeMap.right().value());
1676 createdVfcs.putAll(createdResourcesFromdNodeTypeMap.left().value());
1678 log.debug("************* Going to create all resource instances {}", yamlName);
1679 createResourcesInstancesEither = createResourceInstances(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value());
1681 log.debug("************* Finished to create all resource instances {}", yamlName);
1682 if (createResourcesInstancesEither.isRight()) {
1683 log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
1684 result = createResourcesInstancesEither;
1685 return createResourcesInstancesEither;
1687 resource = createResourcesInstancesEither.left().value();
1688 log.debug("************* Going to create all relations {}", yamlName);
1689 createResourcesInstancesEither = createResourceInstancesRelations(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false);
1691 log.debug("************* Finished to create all relations {}", yamlName);
1693 if (createResourcesInstancesEither.isRight()) {
1694 log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
1695 result = createResourcesInstancesEither;
1698 resource = createResourcesInstancesEither.left().value();
1701 log.debug("************* Going to create positions {}", yamlName);
1702 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, user.getUserId());
1703 log.debug("************* Finished to set positions {}", yamlName);
1704 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
1709 private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
1711 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
1712 List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName(), uploadComponentInstanceInfoMap);
1713 validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
1714 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = null;
1715 if (!extractedVfcsArtifacts.isEmpty() && !extractedVfcToscaNames.isEmpty()) {
1716 for (ImmutablePair<ImmutablePair<String, List<String>>, String> currToscaNamePair : extractedVfcToscaNames) {
1717 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifacts = null;
1718 String currVfcToscaNamespace = currToscaNamePair.getKey().getKey();
1719 List<String> relatedVfcs = currToscaNamePair.getKey().getValue();
1720 List<ArtifactDefinition> currArtifactList = null;
1722 for (String currSubstitute : relatedVfcs) {
1723 if (extractedVfcsArtifacts.containsKey(currSubstitute)) {
1724 if (MapUtils.isEmpty(curNodeTypeArtifacts)) {
1725 curNodeTypeArtifacts = new EnumMap<>(ArtifactOperationEnum.class);
1726 currArtifactList = new ArrayList<>();
1727 curNodeTypeArtifacts.put(ArtifactOperationEnum.Create, currArtifactList);
1729 currArtifactList = curNodeTypeArtifacts.get(ArtifactOperationEnum.Create);
1731 handleAndAddExtractedVfcsArtifacts(currArtifactList, extractedVfcsArtifacts.get(currSubstitute));
1735 if (nodeTypesArtifactsToHandle == null) {
1736 nodeTypesArtifactsToHandle = new HashMap<>();
1738 nodeTypesArtifactsToHandle.put(currVfcToscaNamespace, curNodeTypeArtifacts);
1741 return nodeTypesArtifactsToHandle;
1744 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
1745 List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
1746 artifactsToAdd.stream().forEach(a -> {
1747 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1748 vfcArtifacts.add(a);
1750 log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1756 private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map<String, byte[]> csar, boolean needLock,
1757 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
1759 Map<String, Resource> createdResourcesFromdNodeTypeMap = new HashMap<>();
1760 Either<Map<String, Resource>, ResponseFormat> result = Either.left(createdResourcesFromdNodeTypeMap);
1762 String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE;
1764 if (csar != null && csar.containsKey(yamlFileName)) {
1765 byte[] yamlFileBytes = csar.get(yamlFileName);
1766 String globalTypesYaml = new String(yamlFileBytes, StandardCharsets.UTF_8);
1767 Either<Map<String, Resource>, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock, nodeTypesArtifactsToHandle,
1768 nodeTypesNewCreatedArtifacts);
1769 if (createdNodeTypesFromGlobalTypesTemplateEither.isRight()) {
1770 ResponseFormat responseFormat = createdNodeTypesFromGlobalTypesTemplateEither.right().value();
1771 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1772 return Either.right(responseFormat);
1774 createdResourcesFromdNodeTypeMap.putAll(createdNodeTypesFromGlobalTypesTemplateEither.left().value());
1777 Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
1778 if (createdNodeTypeFromMainTemplateEither.isRight()) {
1779 ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
1780 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1781 return Either.right(responseFormat);
1784 createdResourcesFromdNodeTypeMap.putAll(createdNodeTypeFromMainTemplateEither.left().value());
1786 // add the created node types to the cache although they are not in the
1788 createdResourcesFromdNodeTypeMap.values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1793 private Either<Resource, ResponseFormat> handleCsarArtifacts(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1794 boolean inTransaction) {
1797 String vendorLicenseModelId = null;
1798 String vfLicenseModelId = null;
1800 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
1801 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1802 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1803 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1804 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
1805 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1806 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
1807 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1812 // Specific Behavior for license artifacts
1813 createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1814 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1815 createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1816 Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1818 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarUUID, csar, resource, user, createdArtifacts, shouldLock, inTransaction, artifactOperation);
1819 if (eitherCreateResult.isRight()) {
1820 return Either.right(eitherCreateResult.right().value());
1823 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csar, csarUUID, componentsUtils);
1824 if (artifacsMetaCsarStatus.isLeft()) {
1826 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1827 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1828 Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
1829 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
1830 createArtifactsFromCsar = createResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1832 createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
1833 if (createArtifactsFromCsar.isRight()) {
1834 log.debug("Couldn't create artifacts from artifacts.meta");
1835 return Either.right(createArtifactsFromCsar.right().value());
1838 resource = createArtifactsFromCsar.left().value();
1840 List<GroupDefinition> groupsToDelete = resource.getGroups();
1842 if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
1843 Set<String> artifactsToDelete = new HashSet<String>();
1845 * for (GroupDefinition group : groupsToDelete) { List<String> artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either<GroupDefinition, StorageOperationStatus> deleteGroupEither =
1846 * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus =
1847 * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return
1848 * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
1850 for (String artifactId : artifactsToDelete) {
1851 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
1852 resource, null, null, shouldLock, inTransaction);
1853 if (handleDelete.isRight()) {
1854 log.debug("Couldn't delete artifact {}", artifactId);
1855 return Either.right(handleDelete.right().value());
1858 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1859 if (eitherGetResource.isRight()) {
1860 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
1862 return Either.right(responseFormat);
1865 resource = eitherGetResource.left().value();
1869 return Either.left(resource);
1872 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactFileName, String artifactType,
1873 ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
1874 boolean inTransaction) {
1875 byte[] artifactFileBytes = null;
1877 if (csar.containsKey(artifactPath)) {
1878 artifactFileBytes = csar.get(artifactPath);
1880 Either<Boolean, ResponseFormat> result = Either.left(true);
1881 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
1882 if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
1883 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
1884 null, shouldLock, inTransaction);
1885 if (handleDelete.isRight()) {
1886 result = Either.right(handleDelete.right().value());
1891 if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
1892 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
1896 if (artifactFileBytes != null) {
1897 Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
1898 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction);
1899 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
1900 if (eitherNonMetaArtifacts.isRight()) {
1901 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarUUID, ErrorSeverity.WARNING);
1902 return Either.right(eitherNonMetaArtifacts.right().value());
1908 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
1909 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
1910 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
1911 if (eitherResult.isLeft()) {
1912 createdArtifacts.add(eitherResult.left().value());
1917 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) {
1919 String jsonStr = gson.toJson(json);
1921 String origMd5 = GeneralUtility.calculateMD5ByString(jsonStr);
1922 ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
1923 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
1924 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId,
1925 artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true);
1926 if (uploadArtifactToService.isRight())
1927 return Either.right(uploadArtifactToService.right().value());
1929 return Either.left(uploadArtifactToService.left().value());
1932 public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
1933 boolean shouldLock, boolean inTransaction) {
1935 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, user);
1936 if (parseResourceInfoFromYamlEither.isRight()) {
1937 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
1938 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1939 return Either.right(responseFormat);
1942 List<GroupDefinition> groups = resource.getGroups();
1943 Map<String, ArtifactDefinition> deplymentArtifact = resource.getDeploymentArtifacts();
1944 List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = new ArrayList<ArtifactDefinition>();
1945 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
1946 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
1947 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
1950 int labelCounter = createdDeplymentArtifactsAfterDelete.size();
1952 if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
1953 if (groups != null && !groups.isEmpty()) {
1954 for (GroupDefinition group : groups) {
1955 if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) {
1956 log.debug("failed to update artifacts from csar. List of emty but group not empty");
1957 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
1958 return Either.right(responseFormat);
1962 return createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
1965 // find master in group
1966 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
1968 ////////////////////////////////////// create set parsed
1969 ////////////////////////////////////// artifacts///////////////////////////////////////////
1970 Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
1971 Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
1972 Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>();
1974 for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
1975 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
1976 parsedGroupTemplate.setGroupName("");
1977 Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<ArtifactTemplateInfo>();
1978 parsedArtifactsNames.add(parsedGroupTemplate);
1979 List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
1980 if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
1981 createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
1983 parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
1987 ///////////////////////////////// find artifacts to
1988 ///////////////////////////////// delete////////////////////////////////////////////////////
1990 Set<ArtifactDefinition> artifactsToDelete = new HashSet<ArtifactDefinition>();
1991 Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<String, List<ArtifactDefinition>>();
1992 Map<String, List<String>> dissocArtifactFromGroup = new HashMap<String, List<String>>();
1994 Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
1995 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
1997 // Set<String> deletedArtifactsName = new HashSet<String>();
1998 Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, user, shouldLock, inTransaction, artifactsToDelete, groupToDelete);
1999 if (deletedArtifactsEither.isRight()) {
2000 log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
2002 return Either.right(deletedArtifactsEither.right().value());
2005 List<ArtifactDefinition> deletedArtifacts = deletedArtifactsEither.left().value();
2007 // need to update resource if we updated artifacts
2008 if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) {
2009 for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
2010 ArtifactDefinition artToRemove = null;
2011 for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
2012 if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
2013 artToRemove = artFromResource;
2017 if (artToRemove != null)
2018 createdDeplymentArtifactsAfterDelete.remove(artToRemove);
2023 ////////////// dissociate, associate or create
2024 ////////////// artifacts////////////////////////////
2025 Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarUUID, csar, resource, user, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
2026 dissocArtifactFromGroup, mergedgroup, deletedArtifacts);
2028 if (assDissotiateEither.isRight()) {
2029 log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
2031 return Either.right(assDissotiateEither.right().value());
2034 resource = assDissotiateEither.left().value();
2035 deplymentArtifact = resource.getDeploymentArtifacts();
2036 createdDeplymentArtifactsAfterDelete.clear();
2037 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2038 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2039 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2043 groups = resource.getGroups();
2044 List<GroupDefinition> groupToUpdate = new ArrayList<>();
2045 // update vfModule names
2046 Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
2047 if (groups != null && !groups.isEmpty()) {
2048 Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
2049 if (validateUpdateVfGroupNamesRes.isRight()) {
2050 return Either.right(validateUpdateVfGroupNamesRes.right().value());
2052 List<GroupDefinition> heatGroups = null;
2054 heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2057 for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
2058 GroupDefinition group = null;
2059 Optional<GroupDefinition> opGr = groups.stream().filter(p -> p.getUniqueId().equals(updatedGroupDef.getUniqueId())).findAny();
2060 if (opGr.isPresent()) {
2062 groupToUpdate.add(group);
2064 if (group != null) {
2065 Map<String, String> members = new HashMap<String, String>();
2066 Set<String> artifactsGroup = new HashSet<String>();
2067 artifactsGroup.addAll(group.getArtifacts());
2068 associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
2069 if (!members.isEmpty()) {
2070 group.setMembers(members);
2077 * if (!groupToUpdate.isEmpty()) { Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false,
2078 * true); if (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); return Either.right(assotiateGroupEither.right().value());
2085 //////////////// create new artifacts in update
2086 //////////////// flow////////////////////////////
2087 List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<ArtifactTemplateInfo>();
2089 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2090 ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
2091 boolean isNewGroup = true;
2092 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2093 Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
2094 Set<ArtifactDefinition> group = groupArtifacts.keySet();
2095 for (ArtifactDefinition artifactInfo : group) {
2096 if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
2097 parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
2103 newArtifactsGroup.add(parsedArtifactMaster);
2106 if (!newArtifactsGroup.isEmpty()) {
2107 Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
2108 int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
2109 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter);
2110 if (validateGroupNamesRes.isRight()) {
2111 return Either.right(validateGroupNamesRes.right().value());
2113 Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
2114 if (resStatus.isRight())
2119 if (!groupForAssociateWithMembers.isEmpty()) {
2121 List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
2123 Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId);
2124 if (updateVersionEither.isRight()) {
2125 log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
2127 return Either.right(updateVersionEither.right().value());
2132 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2133 if (eitherGerResource.isRight()) {
2134 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2136 return Either.right(responseFormat);
2139 return Either.left(eitherGerResource.left().value());
2143 private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
2144 Map<String, List<ArtifactDefinition>> groupToDelete) {
2145 List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
2146 String resourceId = resource.getUniqueId();
2147 if (!artifactsToDelete.isEmpty()) {
2148 for (ArtifactDefinition artifact : artifactsToDelete) {
2149 String artifactType = artifact.getArtifactType();
2150 ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
2151 if (artifactTypeEnum == ArtifactTypeEnum.HEAT_ENV) {
2154 * Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if
2155 * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact {} . status is {}", artifact.getUniqueId(), status); ActionStatus
2156 * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); }
2158 * deletedArtifacts.add(removeArifactFromGraph.left().value());
2164 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
2165 null, null, shouldLock, inTransaction);
2166 if (handleDelete.isRight()) {
2167 return Either.right(handleDelete.right().value());
2170 deletedArtifacts.add(handleDelete.left().value().left().value());
2175 if (!groupToDelete.isEmpty()) {
2176 log.debug("try to delete group");
2177 List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
2178 List<GroupDefinition> groups = resource.getGroups();
2179 for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
2180 Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
2181 if (op.isPresent()) {
2182 groupDefinitionstoDelete.add(op.get());
2186 if (!groupDefinitionstoDelete.isEmpty()) {
2187 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete);
2188 if (prepareGroups.isRight()) {
2189 return Either.right(prepareGroups.right().value());
2193 return Either.left(deletedArtifacts);
2196 private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
2197 boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<String, List<String>> dissocArtifactFromGroup, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
2198 Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
2199 Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
2200 Either<Resource, ResponseFormat> resEither = Either.left(resource);
2201 for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
2202 List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts);
2203 if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
2204 List<String> dissList = new ArrayList<String>();
2205 for (ArtifactDefinition art : dissArtifactsInGroup) {
2206 dissList.add(art.getUniqueId());
2207 // String heatEnvId = checkAndGetHeatEnvId(art);
2208 // if (!heatEnvId.isEmpty()) {
2209 // dissList.add(heatEnvId);
2212 dissocArtifactFromGroup.put(entry.getKey().getUniqueId(), dissList);
2215 List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
2216 if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
2217 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
2219 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
2220 if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
2221 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
2224 // Map<String, Set<String>> dissocArtifactFromGroup = new HashMap<String, Set<String>>();
2225 // HashMap<String, Set<String>>();
2226 List<GroupDefinition> dissotiateArtifactsgroups = new ArrayList<GroupDefinition>();
2227 for (Entry<String, List<String>> dissotiateEntry : dissocArtifactFromGroup.entrySet()) {
2229 GroupDefinition dissotiateGroup = new GroupDefinition();
2230 dissotiateGroup.setUniqueId(dissotiateEntry.getKey());
2231 dissotiateGroup.setArtifacts(dissotiateEntry.getValue());
2232 dissotiateArtifactsgroups.add(dissotiateGroup);
2234 if (!dissotiateArtifactsgroups.isEmpty()) {
2236 * log.debug("try to dissociate artifacts from groups "); Either<List<GroupDefinition>, ResponseFormat> dissotiateGroupEither = groupBusinessLogic.dissociateArtifactsFromGroup(resource.getUniqueId(), user.getUserId(),
2237 * ComponentTypeEnum.RESOURCE, dissotiateArtifactsgroups, shouldLock, inTransaction); if (dissotiateGroupEither.isRight()) { log.debug("Failed to dissociate artifacts from groups. Status is {} ", dissotiateGroupEither.right().value());
2238 * resEither = Either.right(dissotiateGroupEither.right().value()); return resEither;
2244 if (!artifactsToUpdateMap.isEmpty()) {
2245 List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>();
2246 for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
2247 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
2248 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
2249 Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifact.getKey(), artifact.getValue(), updatedArtifacts,
2250 artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
2251 if (updateArtifactEither.isRight()) {
2252 log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
2253 resEither = Either.right(updateArtifactEither.right().value());
2263 List<GroupDefinition> associateArtifactGroup = new ArrayList<GroupDefinition>();
2265 for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
2266 List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
2267 Set<String> arifactsUids = new HashSet<String>();
2268 for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
2274 boolean isCreate = true;
2275 for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
2276 if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
2277 arifactsUids.add(createdArtifact.getUniqueId());
2279 String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
2280 if (!heatEnvId.isEmpty()) {
2281 arifactsUids.add(heatEnvId);
2282 Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
2283 if (op.isPresent()) {
2284 this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
2293 if (isCreate) { // check if already created
2294 for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
2295 if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
2296 arifactsUids.add(createdNewArtifact.getUniqueId());
2298 String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
2299 if (!heatEnvId.isEmpty()) {
2300 arifactsUids.add(heatEnvId);
2308 Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
2309 if (createArtifactEither.isRight()) {
2310 resEither = Either.right(createArtifactEither.right().value());
2313 ArtifactDefinition createdArtifact = createArtifactEither.left().value();
2314 arifactsUids.add(createdArtifact.getUniqueId());
2315 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
2316 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2317 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2318 resource.getName(), user, resource, null);
2319 if (createHeatEnvPlaceHolder.isRight()) {
2320 return Either.right(createHeatEnvPlaceHolder.right().value());
2322 String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
2323 arifactsUids.add(heatEnvId);
2328 if (arifactsUids.size() > 0) {
2329 List<String> artifactsToAssociate = new ArrayList<String>();
2330 artifactsToAssociate.addAll(arifactsUids);
2331 GroupDefinition assotiateGroup = new GroupDefinition();
2332 assotiateGroup.setUniqueId(associateEntry.getKey().getUniqueId());
2333 assotiateGroup.setArtifacts(artifactsToAssociate);
2334 associateArtifactGroup.add(assotiateGroup);
2340 * if (!associateArtifactGroup.isEmpty()) {
2342 * log.debug("Try to associate artifacts to groups.");
2344 * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
2345 * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
2350 ComponentParametersView parametersView = new ComponentParametersView();
2351 parametersView.disableAll();
2352 parametersView.setIgnoreComponentInstances(false);
2353 parametersView.setIgnoreUsers(false);
2354 parametersView.setIgnoreArtifacts(false);
2355 parametersView.setIgnoreGroups(false);
2357 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2359 if (eitherGerResource.isRight()) {
2360 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2362 resEither = Either.right(responseFormat);
2366 resEither = Either.left(eitherGerResource.left().value());
2370 private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
2371 Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
2372 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
2373 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2374 Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
2375 boolean isNeedToDeleteGroup = true;
2376 List<ArtifactDefinition> listToDelete = null;
2377 for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
2378 listToDelete = createdArtifactMap.get(maserArtifact);
2379 for (ArtifactDefinition artToDelete : listToDelete) {
2380 findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
2382 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
2383 if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
2384 MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
2385 mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
2386 mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
2387 mergedgroup.put(groupListEntry.getKey(), mergedGroup);
2388 isNeedToDeleteGroup = false;
2394 if (isNeedToDeleteGroup) {
2395 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
2402 private Set<String> findArtifactsNotInGroupToDelete(List<GroupDefinition> groups, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete) {
2403 Set<String> artifactNotInGroupSet = new HashSet<String>();
2404 for (ArtifactDefinition artifact : createdDeplymentArtifactsAfterDelete) {
2405 boolean needToDelete = true;
2406 if (artifact.getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL) || artifact.getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
2408 if (groups != null) {
2409 for (GroupDefinition group : groups) {
2410 List<String> groupArtifactIds = group.getArtifacts();
2411 if (groupArtifactIds == null || groupArtifactIds.isEmpty()) {
2414 for (String groupArtifactid : groupArtifactIds) {
2415 if (groupArtifactid.equalsIgnoreCase(artifact.getUniqueId()))
2416 needToDelete = false;
2423 artifactNotInGroupSet.add(artifact.getUniqueId());
2425 return artifactNotInGroupSet;
2428 private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
2429 List<ArtifactDefinition> createdDeplymentArtifacts) {
2430 boolean isNeedToDeleteArtifact = true;
2431 String artifactType = artifact.getArtifactType();
2432 ArtifactDefinition generatedFromArt = null;
2433 if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
2434 Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
2436 generatedFromArt = op.get();
2440 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2441 Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
2442 for (ArtifactTemplateInfo template : artifactsNames) {
2443 if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
2444 isNeedToDeleteArtifact = false;
2448 if (generatedFromArt != null) {
2449 if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
2450 isNeedToDeleteArtifact = false;
2458 if (isNeedToDeleteArtifact) {
2459 artifactsToDelete.add(artifact);
2464 private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
2465 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>();
2467 for (GroupDefinition group : groups) {
2468 Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>();
2469 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
2470 List<String> artifactsList = group.getArtifacts();
2471 if (artifactsList != null && !artifactsList.isEmpty()) {
2473 ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList);
2474 if (masterArtifact != null)
2475 gupsMap.put(masterArtifact, artifacts);
2476 groupArtifact.put(group, gupsMap);
2480 return groupArtifact;
2483 private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
2485 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2486 parsedArtifactsName.add(parsedGroupTemplate);
2487 List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
2488 if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
2489 createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
2494 public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
2495 boolean shouldLock, boolean inTransaction) {
2497 log.debug("parseResourceArtifactsInfoFromFile start");
2498 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, user);
2499 if (parseResourceInfoFromYamlEither.isRight()) {
2500 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2501 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2502 return Either.right(responseFormat);
2504 log.debug("parseResourceArtifactsInfoFromFile end");
2506 log.debug("createResourceArtifacts start");
2507 Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
2508 if (respStatus.isRight()) {
2511 log.debug("createResourceArtifacts end");
2512 log.debug("getResource start");
2513 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2514 log.debug("getResource end");
2515 if (eitherGerResource.isRight()) {
2516 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2518 return Either.right(responseFormat);
2521 return Either.left(eitherGerResource.left().value());
2525 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList,
2526 List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
2527 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2528 List<GroupDefinition> createdGroups = resource.getGroups();
2529 List<GroupDefinition> heatGroups = null;
2530 if (createdGroups != null && !createdGroups.isEmpty()) {
2531 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2534 List<GroupDefinition> needToAdd = new ArrayList<>();
2535 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2536 String groupName = groupTemplateInfo.getGroupName();
2537 Set<String> artifactsGroup = new HashSet<String>();
2538 Set<String> artifactsUUIDGroup = new HashSet<String>();
2540 resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
2541 if (resStatus.isRight())
2544 Map<String, String> members = new HashMap<String, String>();
2545 associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
2547 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2548 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2550 GroupDefinition groupDefinition = new GroupDefinition();
2551 groupDefinition.setName(groupName);
2552 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2553 groupDefinition.setArtifacts(artifactsList);
2554 groupDefinition.setArtifactsUuid(artifactsUUIDList);
2556 if (!members.isEmpty())
2557 groupDefinition.setMembers(members);
2559 List<GroupProperty> properties = new ArrayList<GroupProperty>();
2560 GroupProperty prop = new GroupProperty();
2561 prop.setName(Constants.IS_BASE);
2562 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2564 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2565 createdArtifacts.addAll(createdNewArtifacts);
2566 createdArtifacts.addAll(artifactsFromResource);
2567 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2568 if (getLatestGroupTypeRes.isRight()) {
2569 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2571 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2572 groupDefinition.convertFromGroupProperties(properties);
2574 properties.add(prop);
2575 groupDefinition.convertFromGroupProperties(properties);
2576 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2577 // if (createGroup.isRight())
2578 // return Either.right(createGroup.right().value());
2579 needToAdd.add(groupDefinition);
2581 ComponentParametersView componentParametersView = new ComponentParametersView();
2582 componentParametersView.disableAll();
2583 componentParametersView.setIgnoreArtifacts(false);
2584 componentParametersView.setIgnoreGroups(false);
2585 componentParametersView.setIgnoreComponentInstances(false);
2587 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2588 if (component.isRight()) {
2589 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2591 resource = component.left().value();
2593 Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, needToAdd);
2594 if (addGroups.isRight())
2595 return Either.right(addGroups.right().value());
2600 private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
2601 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
2602 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2603 String artifactFileName = artifactTemplateInfo.getFileName();
2604 String artifactUid = "";
2605 String artifactUUID = "";
2606 String artifactEnvUid = "";
2607 boolean alreadyExist = false;
2609 // check if artifacts already exist
2610 if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
2611 for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
2612 if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
2613 artifactUid = artifactFromResource.getUniqueId();
2614 artifactUUID = artifactFromResource.getArtifactUUID();
2615 if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2616 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
2617 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2618 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
2620 alreadyExist = true;
2621 artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
2628 if (!alreadyExist) {
2629 for (ArtifactDefinition createdArtifact : createdArtifacts) {
2630 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
2631 artifactUid = createdArtifact.getUniqueId();
2632 artifactUUID = createdArtifact.getArtifactUUID();
2634 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2635 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
2636 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2637 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
2639 alreadyExist = true;
2640 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
2646 // if not exist need to create
2647 if (!alreadyExist) {
2649 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
2650 if (newArtifactEither.isRight()) {
2651 resStatus = Either.right(newArtifactEither.right().value());
2654 ArtifactDefinition newArtifact = newArtifactEither.left().value();
2655 artifactUid = newArtifact.getUniqueId();
2656 artifactUUID = newArtifact.getArtifactUUID();
2657 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
2658 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2659 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2660 resource.getName(), user, resource, null);
2661 if (createHeatEnvPlaceHolder.isRight()) {
2662 return Either.right(createHeatEnvPlaceHolder.right().value());
2664 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
2668 artifactsGroup.add(artifactUid);
2669 artifactsUUIDGroup.add(artifactUUID);
2670 if (!artifactEnvUid.isEmpty()) {
2671 artifactsGroup.add(artifactEnvUid);
2674 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
2675 if (relatedArtifacts != null) {
2676 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
2677 resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
2678 if (resStatus.isRight())
2685 private Either<Resource, ResponseFormat> createResourceArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
2686 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
2688 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2690 Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
2692 for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
2693 if (groupTemplateList != null) {
2694 resStatus = createGroupDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
2695 if (resStatus.isRight())
2704 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2705 ArtifactOperationInfo artifactOperation) {
2707 Either<Resource, ResponseFormat> resStatus = null;
2708 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2711 List<NonMetaArtifactInfo> artifactPathAndNameList =
2712 // Stream of file paths contained in csar
2713 csar.entrySet().stream()
2714 // Filter in only VF artifact path location
2715 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
2716 // Validate and add warnings
2717 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2718 // Filter in Non Warnings
2719 .filter(e -> e.isLeft())
2720 // Convert from Either to NonMetaArtifactInfo
2721 .map(e -> e.left().value())
2723 .collect(Collectors.toList());
2725 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2727 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
2728 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2729 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
2731 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, user);
2733 if (findVfCsarArtifactsToHandleRes.isRight()) {
2734 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2736 if (resStatus == null) {
2737 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2740 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2741 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
2743 Optional<ResponseFormat> optionalCreateInDBError =
2744 // Stream of artifacts to be created
2745 currArtifactOperationPair.getValue().stream()
2746 // create each artifact
2747 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2748 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
2750 // filter in only error
2751 .filter(e -> e.isRight()).
2752 // Convert the error from either to ResponseFormat
2753 map(e -> e.right().value()).
2754 // Check if an error occurred
2756 // Error found on artifact Creation
2757 if (optionalCreateInDBError.isPresent()) {
2758 resStatus = Either.right(optionalCreateInDBError.get());
2763 if (resStatus == null) {
2764 resStatus = Either.left(resource);
2766 } catch (Exception e) {
2767 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2768 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2770 CsarUtils.handleWarningMessages(collectedWarningMessages);
2775 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2777 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2778 // collect all Deployment and Informational artifacts of VF
2779 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2780 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2782 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2783 existingArtifacts.addAll(resource.getArtifacts().values());
2785 existingArtifacts = existingArtifacts.stream()
2786 // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
2787 .filter(this::isNonMetaArtifact).collect(Collectors.toList());
2789 List<String> artifactsToIgnore = new ArrayList<>();
2790 // collect IDs of Artifacts of VF which belongs to any group
2791 if (resource.getGroups() != null) {
2792 resource.getGroups().stream().forEach(g -> {
2793 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
2794 artifactsToIgnore.addAll(g.getArtifacts());
2797 existingArtifacts = existingArtifacts.stream()
2798 // filter artifacts which belongs to any group
2799 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
2800 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2803 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2804 boolean result = true;
2805 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2811 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2812 boolean result = true;
2813 if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2819 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
2820 int labelCounter, boolean shouldLock, boolean inTransaction) {
2821 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2822 List<GroupDefinition> createdGroups = resource.getGroups();
2823 List<GroupDefinition> heatGroups = null;
2824 if (createdGroups != null && !createdGroups.isEmpty()) {
2826 // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
2827 // e.getArtifacts().stream()).filter(p ->
2828 // relevantArtifactTypes.contains(p.getArtifactType()
2829 // )).collect(Collectors.toList());
2830 // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
2831 // e -> e.getProperties().stream().filter(p ->
2832 // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
2833 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2836 List<GroupDefinition> needToCreate = new ArrayList<>();
2837 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2838 String groupName = groupTemplateInfo.getGroupName();
2839 Set<String> artifactsGroup = new HashSet<String>();
2840 Set<String> artifactsUUIDGroup = new HashSet<String>();
2842 log.debug("createDeploymentArtifactsFromCsar start");
2843 resStatus = createDeploymentArtifactFromCsar(csarUUID, ARTIFACTS_PATH, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
2844 log.debug("createDeploymentArtifactsFromCsar end");
2845 if (resStatus.isRight())
2848 Map<String, String> members = new HashMap<String, String>();
2849 associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
2851 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2852 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2854 GroupDefinition groupDefinition = new GroupDefinition();
2855 groupDefinition.setName(groupName);
2856 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2857 groupDefinition.setArtifacts(artifactsList);
2858 groupDefinition.setArtifactsUuid(artifactsUUIDList);
2860 if (!members.isEmpty())
2861 groupDefinition.setMembers(members);
2862 List<GroupProperty> properties = new ArrayList<GroupProperty>();
2863 GroupProperty prop = new GroupProperty();
2864 prop.setName(Constants.IS_BASE);
2865 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2866 properties.add(prop);
2867 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2868 if (getLatestGroupTypeRes.isRight()) {
2869 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2871 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2872 groupDefinition.convertFromGroupProperties(properties);
2873 log.debug("createGroup start");
2875 // Since in these groups we handle only artifacts, then no need to
2876 // fetch component instances
2878 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2879 // log.debug("createGroup end");
2880 // if (createGroup.isRight())
2881 // return Either.right(createGroup.right().value());
2882 needToCreate.add(groupDefinition);
2885 ComponentParametersView componentParametersView = new ComponentParametersView();
2886 componentParametersView.disableAll();
2887 componentParametersView.setIgnoreUsers(false);
2888 componentParametersView.setIgnoreArtifacts(false);
2889 componentParametersView.setIgnoreGroups(false);
2891 componentParametersView.setIgnoreComponentInstances(false);
2893 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2894 if (component.isRight()) {
2895 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2898 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), user, ComponentTypeEnum.RESOURCE, needToCreate);
2899 if (createGroups.isRight()) {
2900 return Either.right(createGroups.right().value());
2906 public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
2907 Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
2908 vfModuleProperties.entrySet().forEach(p -> {
2909 GroupProperty prop = new GroupProperty();
2910 prop.setName(p.getKey());
2912 prop.setValue(p.getValue().getForBaseModule());
2913 prop.setDefaultValue(p.getValue().getForBaseModule());
2915 prop.setValue(p.getValue().getForNonBaseModule());
2916 prop.setDefaultValue(p.getValue().getForNonBaseModule());
2918 properties.add(prop);
2921 GroupProperty proplabel = new GroupProperty();
2922 proplabel.setName("vf_module_label");
2924 Matcher matcher = pattern.matcher(moduleName);
2926 if (matcher.find()) {
2927 proplabel.setValue(matcher.group(1));
2928 proplabel.setDefaultValue(matcher.group(1));
2930 proplabel.setValue(moduleName);
2931 proplabel.setDefaultValue(moduleName);
2933 properties.add(proplabel);
2935 GroupProperty propvolume = new GroupProperty();
2936 propvolume.setName("volume_group");
2937 boolean isVolume = false;
2938 for (String artifactId : artifactsInGroup) {
2939 ArtifactDefinition artifactDef = null;
2940 artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
2941 if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
2946 propvolume.setValue(String.valueOf(isVolume));
2947 propvolume.setDefaultValue(String.valueOf(isVolume));
2948 properties.add(propvolume);
2949 mergeWithGroupTypeProperties(properties, groupType.getProperties());
2953 private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
2955 Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
2956 for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
2957 if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
2958 properties.add(new GroupProperty(groupTypeProperty));
2963 private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
2964 for (ArtifactDefinition artifact : createdArtifacts) {
2965 if (artifact.getUniqueId().equals(artifactId)) {
2972 private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
2973 if (heatGroups != null && !heatGroups.isEmpty()) {
2974 for (GroupDefinition heatGroup : heatGroups) {
2975 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
2976 if (grpoupProps != null) {
2977 Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
2978 if (op.isPresent()) {
2979 GroupProperty prop = op.get();
2980 String heatFileNAme = prop.getValue();
2981 if (null == heatFileNAme || heatFileNAme.isEmpty())
2983 List<ArtifactDefinition> artifacts = new ArrayList();
2984 for (String artifactId : artifactsGroup) {
2985 Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
2986 if (opArt.isPresent()) {
2987 artifacts.add(opArt.get());
2989 if (artifactsFromResource != null) {
2990 opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
2991 if (opArt.isPresent()) {
2992 artifacts.add(opArt.get());
2996 Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
2997 if (resOp.isPresent()) {
2998 members.putAll(heatGroup.getMembers());
3007 private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(String csarUUID, String artifactPath, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
3008 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3009 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
3010 String artifactFileName = artifactTemplateInfo.getFileName();
3011 String artifactUid = "";
3012 String artifactEnvUid = "";
3013 String artifactUUID = "";
3014 boolean alreadyExist = false;
3016 // check if artifacts already exist
3017 for (ArtifactDefinition createdArtifact : createdArtifacts) {
3018 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
3019 artifactUid = createdArtifact.getUniqueId();
3020 artifactUUID = createdArtifact.getArtifactUUID();
3021 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3022 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
3023 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3024 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
3026 alreadyExist = true;
3027 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
3031 // if not exist need to create
3032 if (!alreadyExist) {
3034 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3035 if (newArtifactEither.isRight()) {
3036 resStatus = Either.right(newArtifactEither.right().value());
3039 ArtifactDefinition newArtifact = newArtifactEither.left().value();
3040 artifactUid = newArtifact.getUniqueId();
3041 artifactUUID = newArtifact.getArtifactUUID();
3043 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
3044 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3045 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
3046 resource.getName(), user, resource, null);
3047 if (createHeatEnvPlaceHolder.isRight()) {
3048 return Either.right(createHeatEnvPlaceHolder.right().value());
3050 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
3054 artifactsGroup.add(artifactUid);
3055 artifactsUUIDGroup.add(artifactUUID);
3056 if (!artifactEnvUid.isEmpty()) {
3057 artifactsGroup.add(artifactEnvUid);
3060 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3061 if (relatedArtifacts != null) {
3062 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
3063 resStatus = createDeploymentArtifactFromCsar(csarUUID, artifactPath, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3064 if (resStatus.isRight())
3071 private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
3072 String artifactEnvUid = "";
3073 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
3074 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3075 artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
3077 return artifactEnvUid;
3080 private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
3081 List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3082 final String artifactFileName = artifactTemplateInfo.getFileName();
3083 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath + artifactFileName, artifactFileName, componentsUtils);
3084 if (artifactContententStatus.isRight()) {
3085 return Either.right(artifactContententStatus.right().value());
3087 labelCounter += createdArtifacts.size();
3089 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3091 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3092 shoudLock, inTransaction);
3094 if (uploadArtifactToService.isRight())
3095 return Either.right(uploadArtifactToService.right().value());
3097 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3098 if (currentInfo.getHeatParameters() != null) {
3100 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, false);
3101 if (updateEnvEither.isRight()) {
3102 log.debug("failed to update parameters to artifact {}", artifactFileName);
3103 return Either.right(updateEnvEither.right().value());
3106 currentInfo = updateEnvEither.left().value();
3110 createdArtifacts.add(currentInfo);
3112 return Either.left(currentInfo);
3116 private Either<ArtifactDefinition, ResponseFormat> createInformationalArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, int labelCounter, boolean shoudLock,
3117 boolean inTransaction) {
3118 final String artifactFileName = artifactTemplateInfo.getFileName();
3119 String artifactPath = CsarUtils.ARTIFACTS_PATH + CsarUtils.INFORMATIONAL_ARTIFACTS + artifactFileName;
3120 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath, artifactFileName, componentsUtils);
3121 if (artifactContententStatus.isRight())
3122 return Either.right(artifactContententStatus.right().value());
3124 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3126 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3127 shoudLock, inTransaction);
3129 if (uploadArtifactToService.isRight())
3130 return Either.right(uploadArtifactToService.right().value());
3132 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3134 return Either.left(currentInfo);
3138 private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
3139 List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
3141 Either<ArtifactDefinition, ResponseFormat> resStatus = null;
3142 String artifactFileName = artifactTemplateInfo.getFileName();
3143 String artifactUid = "";
3145 // check if artifacts already exist
3146 for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
3147 if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
3148 artifactUid = updatedArtifact.getUniqueId();
3149 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3150 log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
3151 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3152 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
3155 resStatus = Either.left(updatedArtifact);
3161 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
3162 if (artifactContententStatus.isRight()) {
3163 resStatus = Either.right(artifactContententStatus.right().value());
3167 Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
3168 oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
3170 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
3171 shouldLock, inTransaction);
3173 if (uploadArtifactToService.isRight()) {
3174 resStatus = Either.right(uploadArtifactToService.right().value());
3177 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3179 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, true);
3180 if (updateEnvEither.isRight()) {
3181 log.debug("failed to update parameters to artifact {}", artifactFileName);
3182 resStatus = Either.right(updateEnvEither.right().value());
3185 // TODO evg update env time ( must be separate US for this!!!!)
3187 artifactUid = updateEnvEither.left().value().getUniqueId();
3188 updatedArtifacts.add(updateEnvEither.left().value());
3189 resStatus = Either.left(updateEnvEither.left().value());
3195 private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
3196 Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
3197 if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
3199 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
3201 if (artifactparamsStatus.isRight()) {
3202 resStatus = Either.right(artifactparamsStatus.right().value());
3205 Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
3207 * if (propsStatus.isRight()) {
3209 * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
3211 if (propsStatus.isLeft()) {
3212 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
3213 List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
3214 // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3216 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3219 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3221 paramName = heatEnvParam.getName();
3222 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3223 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3225 String updatedParamValue = heatEnvParam.getCurrentValue();
3226 if (updatedParamValue == null)
3227 updatedParamValue = heatEnvParam.getDefaultValue();
3228 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3229 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3230 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3231 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3232 resStatus = Either.right(responseFormat);
3235 currHeatParam.setCurrentValue(HeatParameterType.isValidType(currHeatParam.getType()).getConverter().convert(updatedParamValue, null, null));
3236 // newHeatEnvParams.add(currHeatParam);
3241 currentInfo.setListHeatParameters(currentHeatEnvParams);
3242 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
3243 if (updateArifactOnResource.isRight()) {
3244 log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
3245 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3251 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3252 Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
3253 if (op.isPresent()) {
3254 ArtifactDefinition artifactInfoHeatEnv = op.get();
3255 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
3256 if (updateArifactOnResource.isRight()) {
3257 log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
3258 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3265 private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
3266 // extract heat parameters
3267 String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
3268 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
3269 if (heatParameters.isRight()) {
3270 log.debug("File {} is not in expected key-value form in csar ", fileName);
3271 BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR);
3272 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
3275 return Either.left(heatParameters.left().value());
3279 private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) {
3281 Map<String, Object> json = new HashMap<String, Object>();
3282 String artifactName = artifactTemplateInfo.getFileName();
3284 json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
3285 json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
3286 json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
3288 // DE250204: There is no need to check if base64 encoding.
3290 // String encodedPayload = new String(artifactContentent);
3291 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3292 // if (!isEncoded) {
3293 String encodedPayload = Base64.encodeBase64String(artifactContentent);
3295 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3296 String displayName = artifactName;
3297 if (artifactName.lastIndexOf(".") > 0)
3298 displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
3299 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3300 String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
3301 json.put(Constants.ARTIFACT_LABEL, label);
3302 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
3303 List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3304 json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
3305 : requiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
3309 private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
3310 List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3312 Map<String, Object> json = new HashMap<String, Object>();
3313 if (artifactId != null && !artifactId.isEmpty())
3314 json.put(Constants.ARTIFACT_ID, artifactId);
3316 json.put(Constants.ARTIFACT_NAME, artifactName);
3317 json.put(Constants.ARTIFACT_TYPE, artifactType);
3318 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3320 String encodedPayload = new String(artifactContentent);
3322 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3323 // if (!isEncoded) {
3324 log.debug("payload is encoded. perform decode");
3325 encodedPayload = Base64.encodeBase64String(artifactContentent);
3328 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3329 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3330 json.put(Constants.ARTIFACT_LABEL, label);
3331 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3332 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3333 : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
3337 private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
3340 JsonObject jsonElement = new JsonObject();
3341 jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
3343 JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
3344 if (importStructureElement == null || importStructureElement.isJsonNull()) {
3345 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3346 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3347 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3350 Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>();
3351 artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
3352 if (artifactTemplateMap.isEmpty()) {
3353 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3354 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3355 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3358 Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
3359 Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>();
3360 List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
3361 for (String artifactsTypeKey : artifactsTypeKeys) {
3363 List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
3364 Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
3365 if (artifactTemplateInfoListPairStatus.isRight()) {
3366 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3367 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3368 return Either.right(artifactTemplateInfoListPairStatus.right().value());
3370 List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
3371 if (artifactTemplateInfoList == null) {
3372 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3373 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3374 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3377 allGroups.addAll(artifactTemplateInfoList);
3378 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList);
3380 int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
3381 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
3382 if (validateGroupNamesRes.isRight()) {
3383 return Either.right(validateGroupNamesRes.right().value());
3385 return Either.left(artifactsMap);
3386 } catch (Exception e) {
3387 log.debug("Artifact file is not in expected format, fileName {}", artifactFileName);
3388 log.debug("failed with exception.", e);
3389 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3390 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3395 private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) {
3396 List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>();
3397 for (Map<String, Object> o : jsonObject) {
3398 Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
3399 if (artifacttemplateInfoStatus.isRight()) {
3400 return Either.right(artifacttemplateInfoStatus.right().value());
3403 ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
3404 if (artifacttemplateInfo != null) {
3405 artifactTemplateInfoList.add(artifacttemplateInfo);
3409 return Either.left(artifactTemplateInfoList);
3412 private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock) {
3413 log.debug("createResourceInstancesRelations try to create relations ");
3414 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3415 if (uploadResInstancesMap == null) {
3416 log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
3417 BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR);
3419 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3420 return Either.right(responseFormat);
3423 if (componentInstancesList == null || componentInstancesList.isEmpty()) {
3424 log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
3425 BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3427 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3428 return Either.right(responseFormat);
3431 log.debug("Before validateAndUpdatePropertyValue");
3432 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
3433 if (allDataTypes.isRight()) {
3434 TitanOperationStatus status = allDataTypes.right().value();
3435 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
3436 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
3440 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
3441 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
3442 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
3443 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
3444 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
3445 Map<String, Resource> originCompMap = new HashMap<>();
3446 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
3448 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3449 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3450 ComponentInstance currentCompInstance = null;
3451 for (ComponentInstance compInstance : componentInstancesList) {
3453 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3454 currentCompInstance = compInstance;
3459 if (currentCompInstance == null) {
3460 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3461 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3462 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3463 return Either.right(responseFormat);
3465 String resourceInstanceId = currentCompInstance.getUniqueId();
3466 Resource originResource = null;
3467 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
3468 Either<Resource, StorageOperationStatus> getPropertyRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
3469 if (getPropertyRes.isRight()) {
3470 log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes);
3471 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getPropertyRes.right().value()), yamlName);
3472 return Either.right(responseFormat);
3474 originResource = getPropertyRes.left().value();
3475 originCompMap.put(originResource.getUniqueId(), originResource);
3477 originResource = originCompMap.get(currentCompInstance.getComponentUid());
3479 if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
3480 instCapabilties.put(currentCompInstance, originResource.getCapabilities());
3481 if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
3482 instRequirements.put(currentCompInstance, originResource.getRequirements());
3483 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
3484 instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
3485 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
3486 instAttributes.put(resourceInstanceId, originResource.getAttributes());
3488 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
3489 if (addPropertiesValueToRiRes.getStatus() != 200) {
3490 return Either.right(addPropertiesValueToRiRes);
3495 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
3496 if (addPropToInst.isRight()) {
3497 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
3498 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
3499 return Either.right(responseFormat);
3502 StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(instArtifacts, resource.getUniqueId(), user);
3503 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3504 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3505 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3506 return Either.right(responseFormat);
3509 addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
3510 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3511 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3512 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3513 return Either.right(responseFormat);
3516 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
3517 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3518 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3519 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3520 return Either.right(responseFormat);
3523 ComponentParametersView parametersView = new ComponentParametersView();
3524 parametersView.disableAll();
3525 parametersView.setIgnoreComponentInstances(false);
3526 parametersView.setIgnoreComponentInstancesProperties(false);
3527 parametersView.setIgnoreCapabilities(false);
3528 parametersView.setIgnoreRequirements(false);
3530 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
3532 if (eitherGerResource.isRight()) {
3533 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
3535 return Either.right(responseFormat);
3539 resource = eitherGerResource.left().value();
3541 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3542 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3543 ComponentInstance currentCompInstance = null;
3544 for (ComponentInstance compInstance : componentInstancesList) {
3546 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3547 currentCompInstance = compInstance;
3552 if (currentCompInstance == null) {
3553 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3554 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3555 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3556 return Either.right(responseFormat);
3559 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
3560 if (addRelationToRiRes.getStatus() != 200) {
3561 return Either.right(addRelationToRiRes);
3565 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
3566 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3567 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3568 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3569 return Either.right(responseFormat);
3572 log.debug("************* in create relations, getResource start");
3574 eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3575 log.debug("************* in create relations, getResource end");
3576 if (eitherGerResource.isRight()) {
3577 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
3579 return Either.right(responseFormat);
3582 return Either.left(eitherGerResource.left().value());
3585 private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3586 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3587 long totalCreateRel = 0;
3588 long totalCreatePropVal = 0;
3590 UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
3592 ComponentInstance currentCompInstance = null;
3594 for (ComponentInstance compInstance : componentInstancesList) {
3596 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3597 currentCompInstance = compInstance;
3603 if (currentCompInstance == null) {
3604 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3605 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3606 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3607 return responseFormat;
3609 String resourceInstanceId = currentCompInstance.getUniqueId();
3611 log.debug("************* addPropertyValuesToRi start");
3612 long startAddProperty = System.currentTimeMillis();
3613 log.debug("************* addPropertyValuesToRi end");
3614 totalCreatePropVal += (System.currentTimeMillis() - startAddProperty);
3615 Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
3616 if (regMap == null) {
3617 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3618 return responseFormat;
3620 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
3622 long startAddRelation = System.currentTimeMillis();
3624 while (nodesRegValue.hasNext()) {
3625 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3627 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3628 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3629 log.debug("Going to create relation {}", uploadRegInfo.getName());
3630 String regName = uploadRegInfo.getName();
3631 String nodeCapName = uploadRegInfo.getNode();
3632 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3633 regCapRelDef.setFromNode(resourceInstanceId);
3634 log.debug("try to find available requirement {} ", regName);
3635 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
3636 if (eitherReqStatus.isRight()) {
3637 log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
3638 return eitherReqStatus.right().value();
3641 RequirementDefinition validReq = eitherReqStatus.left().value();
3642 List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
3643 if (reqAndRelationshipPairList == null)
3644 reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
3645 RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
3646 reqAndRelationshipPair.setRequirement(regName);
3647 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3648 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3649 RelationshipImpl relationship = new RelationshipImpl();
3650 relationship.setType(validReq.getCapability());
3651 reqAndRelationshipPair.setRelationships(relationship);
3653 ComponentInstance currentCapCompInstance = null;
3654 for (ComponentInstance compInstance : componentInstancesList) {
3655 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
3656 currentCapCompInstance = compInstance;
3661 if (currentCapCompInstance == null) {
3662 log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
3663 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3664 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3665 return responseFormat;
3667 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3668 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3669 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
3670 if (aviableCapForRel == null) {
3671 log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
3672 BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
3673 ErrorSeverity.ERROR);
3674 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3675 return responseFormat;
3677 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3678 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3679 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3680 reqAndRelationshipPairList.add(reqAndRelationshipPair);
3681 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3682 relations.add(regCapRelDef);
3687 totalCreateRel += (System.currentTimeMillis() - startAddRelation);
3689 return componentsUtils.getResponseFormat(ActionStatus.OK);
3692 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3693 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3695 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3696 if (propMap != null && propMap.size() > 0) {
3697 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
3700 List<PropertyDefinition> listFromMap = originResource.getProperties();
3701 if (listFromMap == null || listFromMap.isEmpty()) {
3702 log.debug("failed to find properties ");
3703 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3704 return responseFormat;
3706 for (PropertyDefinition prop : listFromMap) {
3707 String propName = prop.getName();
3708 if (!currPropertiesMap.containsKey(propName)) {
3709 currPropertiesMap.put(propName, prop);
3712 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3713 for (List<UploadPropInfo> propertyList : propMap.values()) {
3715 UploadPropInfo propertyInfo = propertyList.get(0);
3716 String propName = propertyInfo.getName();
3717 if (!currPropertiesMap.containsKey(propName)) {
3718 log.debug("failed to find property {} ", propName);
3719 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3720 return responseFormat;
3722 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3723 ComponentInstanceProperty property = null;
3725 String value = null;
3726 List<GetInputValueDataDefinition> getInputs = null;
3727 boolean isValidate = true;
3728 if (propertyInfo.getValue() != null) {
3729 getInputs = propertyInfo.getGet_input();
3730 isValidate = getInputs == null || getInputs.isEmpty();
3732 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3734 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
3736 String innerType = null;
3737 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3739 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
3740 if (validatevalueEiter.isRight()) {
3741 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3744 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
3745 // property.setUniqueId(uniqueId);
3746 property.setValue(validatevalueEiter.left().value());
3748 if (getInputs != null && !getInputs.isEmpty()) {
3749 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3750 for (GetInputValueDataDefinition getInput : getInputs) {
3751 List<InputDefinition> inputs = resource.getInputs();
3752 if (inputs == null || inputs.isEmpty()) {
3753 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
3754 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3757 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3758 if (!optional.isPresent()) {
3759 log.debug("Failed to find input {} ", getInput.getInputName());
3760 // @@TODO error message
3761 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3763 InputDefinition input = optional.get();
3764 getInput.setInputId(input.getUniqueId());
3765 getInputValues.add(getInput);
3767 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3768 if (getInputIndex != null) {
3769 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
3770 if (!optional.isPresent()) {
3771 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3772 // @@TODO error message
3773 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3775 InputDefinition inputIndex = optional.get();
3776 getInputIndex.setInputId(inputIndex.getUniqueId());
3777 getInputValues.add(getInputIndex);
3782 property.setGetInputValues(getInputValues);
3784 instPropList.add(property);
3785 // delete overriden property
3786 currPropertiesMap.remove(property.getName());
3788 // add rest of properties
3789 if (!currPropertiesMap.isEmpty()) {
3790 for (PropertyDefinition value : currPropertiesMap.values()) {
3791 instPropList.add(new ComponentInstanceProperty(value));
3794 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3796 return componentsUtils.getResponseFormat(ActionStatus.OK);
3799 // US740820 Relate RIs according to capability name
3800 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3801 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
3805 return findAviableCapability(validReq, currentCapCompInstance);
3807 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3810 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3811 CapabilityDefinition cap = null;
3812 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3813 if (!capMap.containsKey(validReq.getCapability())) {
3816 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
3817 if (!capByName.isPresent()) {
3820 cap = capByName.get();
3822 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
3823 String leftOccurrences = cap.getLeftOccurrences();
3824 int left = Integer.parseInt(leftOccurrences);
3827 cap.setLeftOccurrences(String.valueOf(left));
3833 // TODO temporary fix - remove specific capability node validation -
3834 // String reqNode = validReq.getNode();
3835 // if (reqNode != null && !reqNode.isEmpty() &&
3836 // !cap.getCapabilitySources().contains(reqNode)) {
3839 // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
3840 // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
3841 // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
3847 private RequirementAndRelationshipPair getReqRelPair(CapabilityDefinition cap) {
3848 RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
3849 relationPair.setCapabilityUid(cap.getUniqueId());
3850 relationPair.setCapability(cap.getName());
3851 relationPair.setCapabilityOwnerId(cap.getOwnerId());
3852 return relationPair;
3855 private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
3856 CapabilityDefinition aviableCapForRel = null;
3857 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3858 if (capMap.containsKey(validReq.getCapability())) {
3859 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3861 for (CapabilityDefinition cap : capList) {
3862 // TODO temporary fix - remove specific capability node
3863 // String reqNode = validReq.getNode();
3864 // if (reqNode != null && !reqNode.isEmpty()) {
3865 // if (!cap.getCapabilitySources().contains(reqNode)) {
3869 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
3870 String leftOccurrences = cap.getLeftOccurrences();
3871 if (leftOccurrences == null) {
3872 leftOccurrences = cap.getMaxOccurrences();
3874 int left = Integer.parseInt(leftOccurrences);
3877 cap.setLeftOccurrences(String.valueOf(left));
3878 aviableCapForRel = cap;
3884 aviableCapForRel = cap;
3889 return aviableCapForRel;
3892 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
3893 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3894 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3895 RequirementDefinition validRegDef = null;
3897 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3898 for (RequirementDefinition reqDef : entry.getValue()) {
3899 if (reqDef.getName().equals(regName)) {
3900 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3901 String leftOccurrences = reqDef.getLeftOccurrences();
3902 if (leftOccurrences == null) {
3903 leftOccurrences = reqDef.getMaxOccurrences();
3905 int left = Integer.parseInt(leftOccurrences);
3908 reqDef.setLeftOccurrences(String.valueOf(left));
3909 validRegDef = reqDef;
3915 validRegDef = reqDef;
3921 if (validRegDef != null) {
3926 for (RequirementDefinition reqDef : list) {
3927 if (reqDef.getName().equals(regName)) {
3928 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3929 String leftOccurrences = reqDef.getLeftOccurrences();
3930 if (leftOccurrences == null) {
3931 leftOccurrences = reqDef.getMaxOccurrences();
3933 int left = Integer.parseInt(leftOccurrences);
3936 reqDef.setLeftOccurrences(String.valueOf(left));
3937 validRegDef = reqDef;
3943 validRegDef = reqDef;
3949 if (validRegDef == null) {
3950 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3951 return Either.right(responseFormat);
3953 return Either.left(validRegDef);
3956 @SuppressWarnings("unchecked")
3957 public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user) {
3959 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
3960 Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
3961 if (toscaElementEither.isRight()) {
3962 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3963 return Either.right(responseFormat);
3966 Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource);
3967 if (createInputsEither.isRight()) {
3968 ResponseFormat responseFormat = createInputsEither.right().value();
3969 return Either.right(responseFormat);
3972 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource);
3973 if (uploadResInstancesEither.isRight()) {
3974 ResponseFormat responseFormat = uploadResInstancesEither.right().value();
3975 return Either.right(responseFormat);
3978 Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource);
3979 if (createGroupsFromYaml.isRight()) {
3980 ResponseFormat responseFormat = createGroupsFromYaml.right().value();
3981 return Either.right(responseFormat);
3984 ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
3985 parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
3986 parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
3987 parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
3989 return Either.left(parsedToscaYamlInfo);
3992 private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
3993 Map<String, Resource> nodeTypeNamespaceMap) {
3995 Either<Resource, ResponseFormat> eitherResource = null;
3996 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3997 if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
3998 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4000 return Either.right(responseFormat);
4003 Map<String, Resource> existingnodeTypeMap = new HashMap<>();
4004 if (nodeTypeNamespaceMap != null && !nodeTypeNamespaceMap.isEmpty()) {
4005 nodeTypeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
4008 Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
4009 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
4010 while (nodesInfoValue.hasNext()) {
4011 log.debug("*************Going to create resource instances {}", yamlName);
4012 Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
4013 UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
4015 // updating type if the type is node type name - we need to take the
4017 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
4018 if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4019 uploadComponentInstanceInfo.setType(nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
4022 eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
4023 if (eitherResource.isRight()) {
4024 return eitherResource;
4026 Resource refResource = eitherResource.left().value();
4028 ComponentInstance componentInstance = new ComponentInstance();
4030 componentInstance.setComponentUid(refResource.getUniqueId());
4032 ComponentTypeEnum containerComponentType = resource.getComponentType();
4033 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
4035 if (containerNodeType.equals(NodeTypeEnum.Resource) && uploadComponentInstanceInfo.getCapabilities() != null) {
4036 Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4037 if (getValidComponentInstanceCapabilitiesRes.isRight()) {
4038 return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
4040 componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
4043 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
4044 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4045 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4046 return Either.right(responseFormat);
4048 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
4049 componentInstance.setName(uploadComponentInstanceInfo.getName());
4050 componentInstance.setIcon(origResource.getIcon());
4052 resourcesInstancesMap.put(componentInstance, origResource);
4055 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
4057 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
4058 if (status != null && status != StorageOperationStatus.OK) {
4059 log.debug("Failed to add component instances to container component {}", resource.getName());
4060 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
4061 eitherResource = Either.right(responseFormat);
4062 return eitherResource;
4067 log.debug("*************Going to get resource {}", resource.getUniqueId());
4068 ComponentParametersView parametersView = new ComponentParametersView();
4069 parametersView.disableAll();
4070 parametersView.setIgnoreComponentInstances(false);
4071 parametersView.setIgnoreUsers(false);
4072 parametersView.setIgnoreInputs(false); // inputs are read when creating
4073 // property values on instances
4074 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
4075 log.debug("*************finished to get resource {}", resource.getUniqueId());
4076 if (eitherGerResource.isRight()) {
4077 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
4079 return Either.right(responseFormat);
4083 if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
4085 log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
4086 BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty");
4087 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4088 return Either.right(responseFormat);
4092 return Either.left(eitherGerResource.left().value());
4095 private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeTypeNamespaceMap) {
4096 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4097 Resource refResource = null;
4098 if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4099 refResource = nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType());
4101 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
4102 if (findResourceEither.isRight()) {
4103 log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4104 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
4105 return Either.right(responseFormat);
4107 refResource = findResourceEither.left().value();
4108 nodeTypeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
4110 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
4111 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4112 log.debug("validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState);
4113 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
4114 return Either.right(responseFormat);
4116 ResourceTypeEnum resourceTypeEnum = refResource.getResourceType();
4117 if (resourceTypeEnum == ResourceTypeEnum.VF) {
4118 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", resourceTypeEnum);
4119 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4120 return Either.right(responseFormat);
4122 return Either.left(refResource);
4125 private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
4126 Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
4127 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
4128 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
4129 if (eitherNodesTemlates.isLeft()) {
4130 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
4132 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
4133 while (nodesNameValue.hasNext()) {
4134 Entry<String, Object> nodeNameValue = nodesNameValue.next();
4135 Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue.getValue());
4136 if (eitherNode.isRight()) {
4137 log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
4138 return Either.right(eitherNode.right().value());
4140 UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
4141 uploadComponentInstanceInfo.setName(nodeNameValue.getKey());
4142 moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
4148 if (moduleComponentInstances.isEmpty()) {
4149 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
4150 return Either.right(responseFormat);
4156 private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Object nodeTemplateJson) {
4158 UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
4159 Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
4162 if (nodeTemplateJson instanceof String) {
4163 String nodeTemplateJsonString = (String) nodeTemplateJson;
4164 nodeTemplateInfo.setType(nodeTemplateJsonString);
4165 } else if (nodeTemplateJson instanceof Map) {
4166 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJson;
4168 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4169 nodeTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4172 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4173 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4174 if (regResponse.isRight())
4175 return Either.right(regResponse.right().value());
4176 if (regResponse.left().value().size() > 0) {
4177 nodeTemplateInfo.setRequirements(regResponse.left().value());
4181 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4182 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4183 if (eitherCapRes.isRight())
4184 return Either.right(eitherCapRes.right().value());
4185 if (eitherCapRes.left().value().size() > 0) {
4186 nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
4189 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4190 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4191 if (regResponse.isRight())
4192 return Either.right(regResponse.right().value());
4193 if (regResponse.left().value().size() > 0) {
4194 nodeTemplateInfo.setProperties(regResponse.left().value());
4199 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
4202 } catch (Exception e) {
4203 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create capability");
4204 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
4205 log.debug("error when creating capability, message:{}", e.getMessage(), e);
4206 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
4212 private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
4213 Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
4214 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
4215 Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
4216 if (toscaProperties.isLeft()) {
4217 Map<String, Object> jsonProperties = toscaProperties.left().value();
4218 for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
4220 String propName = jsonPropObj.getKey();
4221 Object propValue = jsonPropObj.getValue();
4223 if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
4224 log.debug("Ignore property value {}.", propName);
4228 if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
4229 log.debug("Ignore property value {}.", propName);
4232 if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
4233 log.debug("Ignore property value {}.", propName);
4237 if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
4238 log.debug("Ignore property value {}.", propName);
4242 UploadPropInfo propertyDef = new UploadPropInfo();
4243 propertyDef.setValue(propValue);
4244 propertyDef.setName(propName);
4245 if (propValue instanceof Map) {
4246 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4247 propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
4250 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
4251 || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4252 createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
4255 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
4256 propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
4258 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
4259 propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
4261 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
4262 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
4264 propertyDef.setValue(propValue);
4266 } else if (propValue instanceof List) {
4267 List<Object> propValueList = (List<Object>) propValue;
4269 createInputPropList(propertyDef, propValueList);
4270 propertyDef.setValue(propValue);
4273 if (moduleProp.containsKey(propName)) {
4274 moduleProp.get(propName).add(propertyDef);
4276 List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
4277 list.add(propertyDef);
4278 moduleProp.put(propName, list);
4285 private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
4286 for (Object objValue : propValueList) {
4288 if (objValue instanceof Map) {
4289 Map<String, Object> objMap = (Map<String, Object>) objValue;
4290 if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
4291 createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
4293 Set<String> keys = objMap.keySet();
4294 for (String key : keys) {
4295 Object value = objMap.get(key);
4296 if (value instanceof Map) {
4297 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4299 } else if (value instanceof List) {
4300 List<Object> propSubValueList = (List<Object>) value;
4302 createInputPropList(propertyDef, propSubValueList);
4308 } else if (objValue instanceof List) {
4309 List<Object> propSubValueList = (List<Object>) objValue;
4311 createInputPropList(propertyDef, propSubValueList);
4318 private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
4320 if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4321 Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4322 GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
4323 List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
4324 if (getInputs == null) {
4325 getInputs = new ArrayList<GetInputValueDataDefinition>();
4327 if (getInput instanceof String) {
4329 getInputInfo.setInputName((String) getInput);
4330 getInputInfo.setPropName(propName);
4332 } else if (getInput instanceof List) {
4333 List<Object> getInputList = (List<Object>) getInput;
4334 getInputInfo.setPropName(propName);
4335 getInputInfo.setInputName((String) getInputList.get(0));
4336 if (getInputList.size() > 1) {
4337 Object indexObj = getInputList.get(1);
4338 if (indexObj instanceof Integer) {
4339 getInputInfo.setIndexValue((Integer) indexObj);
4340 } else if (indexObj instanceof Float) {
4341 int index = ((Float) indexObj).intValue();
4342 getInputInfo.setIndexValue(index);
4343 } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4344 Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4345 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
4346 getInputInfoIndex.setInputName((String) index);
4347 getInputInfoIndex.setPropName(propName);
4348 getInputInfo.setGetInputIndex(getInputInfoIndex);
4350 getInputInfo.setList(true);
4354 getInputs.add(getInputInfo);
4355 propertyDef.setGet_input(getInputs);
4356 propertyDef.setValue(propValue);
4358 Set<String> keys = propValue.keySet();
4359 for (String key : keys) {
4360 Object value = propValue.get(key);
4361 if (value instanceof Map) {
4362 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4364 } else if (value instanceof List) {
4365 List<Object> valueList = (List<Object>) value;
4366 for (Object o : valueList) {
4367 if (o instanceof Map) {
4368 createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
4381 * private boolean valueContainsStrReplace(Object propValue) {
4383 * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher =
4384 * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); }
4388 * private boolean valueContainsToken(Object propValue) {
4390 * log.debug("valueContainsToken value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsToken value is {}", propValue.getClass()); Matcher matcher = TOKEN_PATTERN.matcher(propValue.toString()); result =
4396 private boolean valueContainsPattern(Pattern pattern, Object propValue) {
4398 log.debug("valueContainsToken value is {}", propValue);
4399 boolean result = false;
4400 if (propValue != null) {
4401 log.debug("valueContainspattern value is {}", propValue.getClass());
4402 Matcher matcher = pattern.matcher(propValue.toString());
4403 result = matcher.find();
4410 private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4411 Map<String, List<UploadCapInfo>> moduleCap = new HashMap<String, List<UploadCapInfo>>();
4412 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
4413 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4414 if (toscaRequirements.isLeft()) {
4415 List<Object> jsonCapabilities = toscaRequirements.left().value();
4417 for (Object jsonCapObj : jsonCapabilities) {
4419 Map<String, Object> capJsonWrapper = (Map<String, Object>) jsonCapObj;
4420 String capName = capJsonWrapper.keySet().iterator().next();
4421 Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJsonWrapper.get(capName));
4422 if (eitherCap.isRight()) {
4423 log.info("error when creating Requirement:{}, for node:{}", capName, nodeTemplateInfo);
4424 return Either.right(eitherCap.right().value());
4426 UploadCapInfo requirementDef = eitherCap.left().value();
4427 requirementDef.setName(capName);
4428 if (moduleCap.containsKey(capName)) {
4429 moduleCap.get(capName).add(requirementDef);
4431 List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
4432 list.add(requirementDef);
4433 moduleCap.put(capName, list);
4444 private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4445 Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
4446 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
4447 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4448 if (toscaRequirements.isLeft()) {
4449 List<Object> jsonRequirements = toscaRequirements.left().value();
4451 for (Object jsonRequirementObj : jsonRequirements) {
4453 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
4454 String requirementName = requirementJsonWrapper.keySet().iterator().next();
4455 Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJsonWrapper.get(requirementName));
4456 if (eitherRequirement.isRight()) {
4457 log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
4458 return Either.right(eitherRequirement.right().value());
4460 UploadReqInfo requirementDef = eitherRequirement.left().value();
4461 requirementDef.setName(requirementName);
4462 if (moduleRequirements.containsKey(requirementName)) {
4463 moduleRequirements.get(requirementName).add(requirementDef);
4465 List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
4466 list.add(requirementDef);
4467 moduleRequirements.put(requirementName, list);
4477 private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
4478 UploadCapInfo capTemplateInfo = new UploadCapInfo();
4479 Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
4481 if (capObject instanceof String) {
4482 String nodeTemplateJsonString = (String) capObject;
4483 capTemplateInfo.setNode(nodeTemplateJsonString);
4484 } else if (capObject instanceof Map) {
4485 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
4487 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4488 capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4490 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4491 capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4493 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
4494 Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
4495 if (validSourceTypesRes.isLeft()) {
4496 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList()));
4499 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4500 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4501 if (regResponse.isRight())
4502 return Either.right(regResponse.right().value());
4503 if (!regResponse.left().value().isEmpty()) {
4504 List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
4505 regResponse.left().value().values().forEach(list -> properties.addAll(list));
4506 if (!properties.isEmpty())
4507 capTemplateInfo.setProperties(properties);
4515 private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
4517 UploadReqInfo regTemplateInfo = new UploadReqInfo();
4518 Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
4520 if (regObject instanceof String) {
4521 String nodeTemplateJsonString = (String) regObject;
4522 regTemplateInfo.setNode(nodeTemplateJsonString);
4523 } else if (regObject instanceof Map) {
4524 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
4526 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4527 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4529 // US740820 Relate RIs according to capability name
4530 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
4531 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
4538 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4539 Either<Resource, ResponseFormat> result = null;
4541 // resource updated with checkout. certify the resource
4542 if (resource.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
4543 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
4544 result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
4548 result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
4549 if (result.isLeft()) {
4550 resource = result.left().value();
4551 result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
4553 if (result.isLeft()) {
4554 resource = result.left().value();
4555 result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
4559 if (result == null || result.isRight()) {
4560 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
4561 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4562 if (inTransaction == false) {
4563 log.debug("operation failed. do rollback");
4564 titanDao.rollback();
4566 } else if (inTransaction == false) {
4567 log.debug("operation success. do commit");
4576 * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
4579 * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
4580 * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
4583 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
4585 // check if resource already exist
4586 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
4587 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4590 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4592 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
4593 if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
4594 result = createResourceByImport(resource, user, isNormative, isInTransaction);
4597 StorageOperationStatus status = latestByName.right().value();
4598 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
4599 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4600 log.debug("resource already exist {}. status={}", resource.getName(), status);
4601 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
4602 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4603 result = Either.right(responseFormat);
4609 else if (latestByName.isLeft()) {
4610 result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock);
4615 StorageOperationStatus status = latestByName.right().value();
4616 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
4617 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
4618 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
4619 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4620 result = Either.right(responseFormat);
4626 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
4627 log.debug("resource with name {} does not exist. create new resource", resource.getName());
4628 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
4629 if (response.isRight()) {
4630 return Either.right(response.right().value());
4632 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
4633 if (createResponse.isRight()) {
4634 return Either.right(createResponse.right().value());
4636 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
4637 ASDCKpiApi.countImportResourcesKPI();
4638 return Either.left(resourcePair);
4643 public boolean isResourceExist(String resourceName) {
4644 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
4645 return latestByName.isLeft();
4648 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock) {
4649 String lockedResourceId = oldResource.getUniqueId();
4650 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState());
4651 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4654 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import");
4655 if (lockResult.isRight()) {
4656 return Either.right(lockResult.right().value());
4660 Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false);
4661 if (prepareResourceForUpdate.isRight()) {
4662 ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
4663 log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage());
4664 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
4665 result = Either.right(prepareResourceForUpdate.right().value());
4668 oldResource = prepareResourceForUpdate.left().value();
4670 mergeOldResourceMetadataWithNew(oldResource, newResource);
4672 Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction);
4673 if (validateFieldsResponse.isRight()) {
4674 result = Either.right(validateFieldsResponse.right().value());
4678 // contact info normalization
4679 newResource.setContactId(newResource.getContactId().toLowerCase());
4680 // non-updatable fields
4681 newResource.setCreatorUserId(user.getUserId());
4682 newResource.setCreatorFullName(user.getFullName());
4683 newResource.setLastUpdaterUserId(user.getUserId());
4684 newResource.setLastUpdaterFullName(user.getFullName());
4685 newResource.setUniqueId(oldResource.getUniqueId());
4686 newResource.setVersion(oldResource.getVersion());
4687 newResource.setInvariantUUID(oldResource.getInvariantUUID());
4688 newResource.setLifecycleState(oldResource.getLifecycleState());
4689 newResource.setUUID(oldResource.getUUID());
4690 newResource.setNormalizedName(oldResource.getNormalizedName());
4691 newResource.setSystemName(oldResource.getSystemName());
4692 if (oldResource.getCsarUUID() != null) {
4693 newResource.setCsarUUID(oldResource.getCsarUUID());
4695 if (oldResource.getImportedToscaChecksum() != null) {
4696 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
4698 newResource.setAbstract(oldResource.isAbstract());
4700 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
4701 newResource.setDerivedFrom(oldResource.getDerivedFrom());
4703 // TODO rhalili: handle artifacts here (delete from old resource and
4705 // TODO rbetzer: remove after migration - in case of resources
4706 // created without tosca artifacts - add the placeholders
4707 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
4708 setToscaArtifactsPlaceHolders(newResource, user);
4710 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
4712 if (overrideResource.isRight()) {
4713 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
4714 componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
4715 result = Either.right(responseFormat);
4719 log.debug("Resource updated successfully!!!");
4720 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4721 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
4723 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
4724 result = Either.left(resourcePair);
4727 if (result == null || result.isRight()) {
4728 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
4729 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4730 log.debug("operation failed. do rollback");
4731 titanDao.rollback();
4732 } else if (inTransaction == false) {
4733 log.debug("operation success. do commit");
4736 if (needLock == true) {
4737 log.debug("unlock resource {}", lockedResourceId);
4738 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4745 * Merge old resource with new. Keep old category and vendor name without change
4747 * @param oldResource
4748 * @param newResource
4750 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4752 // keep old category and vendor name without change
4753 // merge the rest of the resource metadata
4754 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4755 newResource.setTags(oldResource.getTags());
4758 if (newResource.getDescription() == null) {
4759 newResource.setDescription(oldResource.getDescription());
4762 if (newResource.getVendorRelease() == null) {
4763 newResource.setVendorRelease(oldResource.getVendorRelease());
4766 if (newResource.getContactId() == null) {
4767 newResource.setContactId(oldResource.getContactId());
4770 newResource.setCategories(oldResource.getCategories());
4771 newResource.setVendorName(oldResource.getVendorName());
4774 private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) {
4776 Either<Resource, ResponseFormat> result = Either.left(latestResource);
4777 // check if user can edit resource
4778 if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
4780 Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
4781 result = changeState;
4787 public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction) {
4789 Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4790 if (eitherValidation.isRight()) {
4791 return Either.right(eitherValidation.right().value());
4794 eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4795 if (eitherValidation.isRight()) {
4796 return Either.right(eitherValidation.right().value());
4798 eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
4799 if (eitherValidation.isRight()) {
4800 return Either.right(eitherValidation.right().value());
4802 eitherValidation = validateResourceType(user, resource, actionEnum);
4803 if (eitherValidation.isRight()) {
4804 return Either.right(eitherValidation.right().value());
4807 resource.setCreatorUserId(user.getUserId());
4808 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4809 resource.setContactId(resource.getContactId().toLowerCase());
4810 if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
4811 resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VF.name(), resource.getSystemName()));
4814 // Generate invariant UUID - must be here and not in operation since it
4815 // should stay constant during clone
4816 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4817 resource.setInvariantUUID(invariantUUID);
4819 return Either.left(resource);
4822 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
4823 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4824 if (resource.getResourceType() == null) {
4825 log.debug("Invalid resource type for resource");
4826 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4827 eitherResult = Either.right(errorResponse);
4828 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4830 return eitherResult;
4833 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
4834 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4835 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
4836 log.debug("validate interface lifecycle Types Exist");
4837 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
4838 while (intItr.hasNext() && eitherResult.isLeft()) {
4839 InterfaceDefinition interfaceDefinition = intItr.next();
4840 String intType = interfaceDefinition.getUniqueId();
4841 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
4842 if (eitherCapTypeFound.isRight()) {
4843 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4844 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInterfaceMissingError, "Create Resource - validateLifecycleTypesCreate", intType);
4845 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
4846 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
4847 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateLifecycleTypesCreate");
4848 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4849 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
4852 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4853 eitherResult = Either.right(errorResponse);
4854 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4859 return eitherResult;
4862 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4864 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4865 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
4866 log.debug("validate capability Types Exist - capabilities section");
4868 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
4870 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
4871 if (eitherResult.isRight()) {
4872 return Either.right(eitherResult.right().value());
4877 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
4878 log.debug("validate capability Types Exist - requirements section");
4880 for (String type : resource.getRequirements().keySet()) {
4882 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, type, inTransaction);
4883 if (eitherResult.isRight()) {
4884 return Either.right(eitherResult.right().value());
4889 return eitherResult;
4892 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4893 boolean inTransaction) {
4894 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
4895 if (eitherCapTypeFound.isRight()) {
4896 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4897 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", type);
4898 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
4899 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
4900 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
4902 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
4903 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
4904 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4905 eitherResult = Either.right(errorResponse);
4906 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4908 return eitherResult;
4911 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
4912 Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
4913 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
4914 if (eitherCapTypeFound.isRight()) {
4915 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4916 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", typeEntry.getKey());
4917 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
4918 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
4919 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
4921 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
4922 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
4923 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
4924 eitherResult = Either.right(errorResponse);
4925 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4927 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4928 if (capabilityTypeDefinition.getProperties() != null) {
4929 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4930 List<ComponentInstanceProperty> properties = capDef.getProperties();
4931 if (properties == null || properties.isEmpty()) {
4932 properties = new ArrayList<ComponentInstanceProperty>();
4933 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4934 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4935 properties.add(newProp);
4938 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4939 PropertyDefinition porpFromDef = prop.getValue();
4940 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4941 for (ComponentInstanceProperty cip : properties) {
4942 if (!cip.getName().equals(porpFromDef.getName())) {
4943 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
4944 propsToAdd.add(newProp);
4947 if (!propsToAdd.isEmpty()) {
4948 properties.addAll(propsToAdd);
4952 capDef.setProperties(properties);
4955 return eitherResult;
4958 public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
4961 // lock new resource name in order to avoid creation resource with same
4963 if (inTransaction == false) {
4964 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
4965 if (lockResult.isRight()) {
4966 ResponseFormat responseFormat = lockResult.right().value();
4967 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
4968 return Either.right(responseFormat);
4971 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4974 if (resource.deriveFromGeneric()) {
4975 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
4976 if (genericResourceEither.isRight())
4977 return genericResourceEither;
4978 if (resource.shouldGenerateInputs())
4979 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
4982 Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
4983 if (respStatus.isLeft()) {
4984 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
4985 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
4986 ASDCKpiApi.countCreatedResourcesKPI();
4988 componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
4992 if (inTransaction == false) {
4993 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
4998 private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
4999 // validate resource name uniqueness
5000 log.debug("validate resource name");
5001 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
5002 if (eitherValidation.isRight()) {
5003 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
5004 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
5005 return Either.right(errorResponse);
5007 if (eitherValidation.left().value()) {
5008 log.debug("resource with name: {}, already exists", resource.getName());
5009 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5010 return Either.right(errorResponse);
5013 log.debug("send resource {} to dao for create", resource.getName());
5015 createArtifactsPlaceHolderData(resource, user);
5021 log.debug("enrich resource with creator, version and state");
5022 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
5023 resource.setVersion(INITIAL_VERSION);
5024 resource.setHighestVersion(true);
5025 resource.setAbstract(false);
5028 Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
5029 if (createToscaElement.isLeft()) {
5030 return Either.left(createToscaElement.left().value());
5033 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
5035 return Either.right(responseFormat);
5038 private void createArtifactsPlaceHolderData(Resource resource, User user) {
5039 // create mandatory artifacts
5041 // TODO it must be removed after that artifact uniqueId creation will be
5042 // moved to ArtifactOperation
5043 // String resourceUniqueId =
5044 // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
5045 // resource.getResourceVersion());
5047 setInformationalArtifactsPlaceHolder(resource, user);
5048 setDeploymentArtifactsPlaceHolder(resource, user);
5049 setToscaArtifactsPlaceHolders(resource, user);
5052 @SuppressWarnings("unchecked")
5054 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
5055 Resource resource = (Resource) component;
5056 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
5057 if (artifactMap == null) {
5058 artifactMap = new HashMap<String, ArtifactDefinition>();
5060 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts();
5061 if (deploymentResourceArtifacts != null) {
5062 Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
5063 while (iterator.hasNext()) {
5064 Entry<String, Object> currEntry = iterator.next();
5065 boolean shouldCreateArtifact = true;
5066 Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
5067 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
5068 if (object != null) {
5069 List<String> artifactTypes = (List<String>) object;
5070 if (!artifactTypes.contains(resource.getResourceType().name())) {
5071 shouldCreateArtifact = false;
5075 log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey());
5077 if (shouldCreateArtifact) {
5078 if (artifactsBusinessLogic != null) {
5079 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT);
5080 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
5081 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5086 resource.setDeploymentArtifacts(artifactMap);
5089 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
5090 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
5091 if (artifactMap == null) {
5092 artifactMap = new HashMap<String, ArtifactDefinition>();
5094 String resourceUniqueId = resource.getUniqueId();
5095 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
5096 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
5097 List<CategoryDefinition> categories = resource.getCategories();
5098 boolean isCreateArtifact = true;
5099 if (exludeResourceCategory != null) {
5100 String category = categories.get(0).getName();
5101 for (String exlude : exludeResourceCategory) {
5102 if (exlude.equalsIgnoreCase(category)) {
5103 isCreateArtifact = false;
5110 if (informationalResourceArtifacts != null && isCreateArtifact) {
5111 Set<String> keys = informationalResourceArtifacts.keySet();
5112 for (String informationalResourceArtifactName : keys) {
5113 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
5114 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
5115 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5119 resource.setArtifacts(artifactMap);
5129 public ResponseFormat deleteResource(String resourceId, User user) {
5130 ResponseFormat responseFormat;
5131 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5132 if (eitherCreator.isRight()) {
5133 return eitherCreator.right().value();
5136 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
5137 if (resourceStatus.isRight()) {
5138 log.debug("failed to get resource {}", resourceId);
5139 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
5142 Resource resource = resourceStatus.left().value();
5144 StorageOperationStatus result = StorageOperationStatus.OK;
5145 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
5146 if (lockResult.isRight()) {
5147 result = StorageOperationStatus.GENERAL_ERROR;
5148 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5153 result = markComponentToDelete(resource);
5154 if (result.equals(StorageOperationStatus.OK)) {
5155 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5157 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5158 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5160 return responseFormat;
5163 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5164 log.warn("operation failed. do rollback");
5165 titanDao.rollback();
5167 log.debug("operation success. do commit");
5170 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
5175 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
5176 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5177 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5178 if (eitherCreator.isRight()) {
5179 return eitherCreator.right().value();
5182 // Resource resource = null;
5183 Resource resource = null;
5184 StorageOperationStatus result = StorageOperationStatus.OK;
5187 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
5188 if (resourceStatus.isRight()) {
5189 log.debug("failed to get resource {} version {}", resourceName, version);
5190 return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
5193 resource = resourceStatus.left().value();
5196 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5197 log.warn("operation failed. do rollback");
5198 titanDao.rollback();
5199 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5200 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
5202 log.debug("operation success. do commit");
5206 if (resource != null) {
5207 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
5208 if (lockResult.isRight()) {
5209 result = StorageOperationStatus.GENERAL_ERROR;
5210 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5213 result = markComponentToDelete(resource);
5214 if (!result.equals(StorageOperationStatus.OK)) {
5215 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5216 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5217 return responseFormat;
5221 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5222 log.warn("operation failed. do rollback");
5223 titanDao.rollback();
5225 log.debug("operation success. do commit");
5228 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
5231 return responseFormat;
5234 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
5237 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
5238 if (eitherCreator.isRight()) {
5239 return Either.right(eitherCreator.right().value());
5243 // IResourceOperation dataModel = getResourceOperation();
5244 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
5246 if (storageStatus.isRight()) {
5247 log.debug("failed to get resource by id {}", resourceId);
5248 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5250 return Either.left(storageStatus.left().value());
5254 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
5256 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
5257 if (resp.isRight()) {
5258 return Either.right(resp.right().value());
5261 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
5262 if (getResource.isRight()) {
5263 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
5264 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
5266 return Either.left(getResource.left().value());
5270 * updateResourceMetadata
5273 * - modifier data (userId)
5274 * @param inTransaction
5276 * @param resourceIdToUpdate
5277 * - the resource identifier
5278 * @param newResource
5280 * @return Either<Resource, responseFormat>
5282 public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
5284 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
5285 if (resp.isRight()) {
5286 return Either.right(resp.right().value());
5289 // IResourceOperation dataModel = getResourceOperation();
5290 log.debug("Get resource with id {}", resourceIdToUpdate);
5291 boolean needToUnlock = false;
5292 boolean rollbackNeeded = true;
5295 // Either<Resource, StorageOperationStatus> storageStatus =
5296 // dataModel.getResource_tx(resourceIdToUpdate, false);
5297 if (currentResource == null) {
5298 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
5299 if (storageStatus.isRight()) {
5300 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5303 currentResource = storageStatus.left().value();
5305 // verify that resource is checked-out and the user is the last
5307 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
5308 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
5312 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5313 if (!lockResult.equals(StorageOperationStatus.OK)) {
5314 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Upload Artifact - lock " + resourceIdToUpdate + ": " + NodeTypeEnum.Resource);
5315 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
5316 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
5317 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
5318 return Either.right(responseFormat);
5321 needToUnlock = true;
5323 // critical section starts here
5324 // convert json to object
5326 // Update and updated resource must have a non-empty "derivedFrom"
5328 // This code is not called from import resources, because of root
5329 // VF "derivedFrom" should be null (or ignored)
5330 if (!currentResource.getResourceType().equals(ResourceTypeEnum.VF)) {
5331 Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
5332 if (derivedFromNotEmptyEither.isRight()) {
5333 log.debug("for updated resource {}, derived from field is empty", newResource.getName());
5334 return Either.right(derivedFromNotEmptyEither.right().value());
5337 derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
5338 if (derivedFromNotEmptyEither.isRight()) {
5339 log.debug("for current resource {}, derived from field is empty", currentResource.getName());
5340 return Either.right(derivedFromNotEmptyEither.right().value());
5343 newResource.setDerivedFrom(null);
5346 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true);
5347 if (dataModelResponse.isRight()) {
5348 log.debug("failed to update resource metadata!!!");
5349 rollbackNeeded = true;
5350 return Either.right(dataModelResponse.right().value());
5353 log.debug("Resource metadata updated successfully!!!");
5354 rollbackNeeded = false;
5355 return Either.left(dataModelResponse.left().value());
5358 if (!inTransaction) {
5359 if (rollbackNeeded) {
5360 titanDao.rollback();
5367 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5372 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
5374 Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
5375 if (validateResourceFields.isRight()) {
5376 return Either.right(validateResourceFields.right().value());
5378 // Setting last updater and uniqueId
5379 newResource.setContactId(newResource.getContactId().toLowerCase());
5380 newResource.setLastUpdaterUserId(user.getUserId());
5381 newResource.setUniqueId(resourceIdToUpdate);
5382 // Cannot set highest version through UI
5383 newResource.setHighestVersion(currentResource.isHighestVersion());
5384 newResource.setCreationDate(currentResource.getCreationDate());
5386 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
5388 if (processUpdateOfDerivedFrom.isRight()) {
5389 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
5390 return Either.right(processUpdateOfDerivedFrom.right().value());
5393 log.debug("send resource {} to dao for update", newResource.getUniqueId());
5394 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
5396 if (dataModelResponse.isRight()) {
5397 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
5398 return Either.right(responseFormat);
5399 } else if (dataModelResponse.left().value() == null) {
5400 log.debug("No response from updateResource");
5401 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5403 return Either.left(dataModelResponse.left().value());
5407 * validateResourceFieldsBeforeCreate
5410 * - modifier data (userId)
5412 * - IResourceOperation for resource crud
5414 * - Resource object to validate
5415 * @return Either<Boolean, ErrorResponse>
5417 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5418 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
5419 if (componentsFieldsValidation.isRight()) {
5420 return componentsFieldsValidation;
5426 * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5428 * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5433 * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5438 * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5441 // validate category
5442 log.debug("validate category");
5443 Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
5444 if (eitherValidation.isRight()) {
5445 return eitherValidation;
5448 // validate vendor name & release
5449 log.debug("validate vendor name");
5450 eitherValidation = validateVendorName(user, resource, actionEnum);
5451 if (eitherValidation.isRight()) {
5452 return eitherValidation;
5455 log.debug("validate vendor release");
5456 eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
5457 if (eitherValidation.isRight()) {
5458 return eitherValidation;
5461 // validate contact info
5463 * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5467 log.debug("validate cost");
5468 eitherValidation = validateCost(user, resource, actionEnum);
5469 if (eitherValidation.isRight()) {
5470 return eitherValidation;
5473 // validate licenseType
5474 log.debug("validate licenseType");
5475 eitherValidation = validateLicenseType(user, resource, actionEnum);
5476 if (eitherValidation.isRight()) {
5477 return eitherValidation;
5480 // validate template (derived from)
5481 log.debug("validate derived from");
5482 if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
5483 resource.setDerivedFrom(null);
5485 eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
5486 if (eitherValidation.isRight()) {
5487 return Either.right(eitherValidation.right().value());
5490 // warn about non-updatable fields
5491 checkComponentFieldsForOverrideAttempt(resource);
5492 String currentCreatorFullName = resource.getCreatorFullName();
5493 if (currentCreatorFullName != null) {
5494 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5497 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
5498 if (currentLastUpdaterFullName != null) {
5499 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5502 Long currentLastUpdateDate = resource.getLastUpdateDate();
5503 if (currentLastUpdateDate != null) {
5504 log.warn("Resource last update date is automatically set and cannot be updated");
5507 Boolean currentAbstract = resource.isAbstract();
5508 if (currentAbstract != null) {
5509 log.warn("Resource abstract is automatically set and cannot be updated");
5512 return Either.left(true);
5516 * validateResourceFieldsBeforeUpdate
5518 * @param currentResource
5519 * - Resource object to validate
5520 * @return Either<Boolean, ErrorResponse>
5522 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
5524 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5526 // validate resource name
5527 log.debug("validate resource name before update");
5528 Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified);
5529 if (eitherValidation.isRight()) {
5530 return eitherValidation;
5533 // validate description
5534 log.debug("validate description before update");
5535 eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
5536 if (eitherValidation.isRight()) {
5537 return eitherValidation;
5540 log.debug("validate icon before update");
5541 eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5542 if (eitherValidation.isRight()) {
5543 return eitherValidation;
5546 log.debug("validate tags before update");
5547 eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
5548 if (eitherValidation.isRight()) {
5549 return eitherValidation;
5552 log.debug("validate vendor name before update");
5553 eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
5554 if (eitherValidation.isRight()) {
5555 return eitherValidation;
5558 log.debug("validate vendor release before update");
5559 eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
5560 if (eitherValidation.isRight()) {
5561 return eitherValidation;
5564 log.debug("validate contact info before update");
5565 eitherValidation = validateContactId(null, updateInfoResource, null);
5566 if (eitherValidation.isRight()) {
5567 return eitherValidation;
5570 log.debug("validate derived before update");
5571 eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5572 if (eitherValidation.isRight()) {
5573 return eitherValidation;
5576 log.debug("validate category before update");
5577 eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5578 if (eitherValidation.isRight()) {
5579 return eitherValidation;
5582 // warn about non-updatable fields
5583 String currentResourceVersion = currentResource.getVersion();
5584 String updatedResourceVersion = updateInfoResource.getVersion();
5586 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
5587 log.warn("Resource version is automatically set and cannot be updated");
5590 String currentCreatorUserId = currentResource.getCreatorUserId();
5591 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
5593 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
5594 log.warn("Resource Creator UserId is automatically set and cannot be updated");
5597 String currentCreatorFullName = currentResource.getCreatorFullName();
5598 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
5600 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
5601 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5604 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
5605 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
5607 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
5608 log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
5611 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
5612 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
5614 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
5615 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5618 Long currentCreationDate = currentResource.getCreationDate();
5619 Long updatedCreationDate = updateInfoResource.getCreationDate();
5621 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
5622 log.warn("Resource Creation date is automatically set and cannot be updated");
5625 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
5626 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
5628 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
5629 log.warn("Resource last update date is automatically set and cannot be updated");
5632 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
5633 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
5635 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
5636 log.warn("Resource lifecycle state date is automatically set and cannot be updated");
5639 Boolean currentAbstract = currentResource.isAbstract();
5640 Boolean updatedAbstract = updateInfoResource.isAbstract();
5642 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
5643 log.warn("Resource abstract is automatically set and cannot be updated");
5646 Boolean currentHighestVersion = currentResource.isHighestVersion();
5647 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
5649 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
5650 log.warn("Resource highest version is automatically set and cannot be updated");
5653 String currentUuid = currentResource.getUUID();
5654 String updatedUuid = updateInfoResource.getUUID();
5656 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
5657 log.warn("Resource UUID is automatically set and cannot be updated");
5660 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
5661 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
5663 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
5664 log.warn("Resource Type cannot be updated");
5667 updateInfoResource.setResourceType(currentResource.getResourceType());
5669 String currentInvariantUuid = currentResource.getInvariantUUID();
5670 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
5672 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5673 log.warn("Resource invariant UUID is automatically set and cannot be updated");
5674 updateInfoResource.setInvariantUUID(currentInvariantUuid);
5676 return Either.left(true);
5680 * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName();
5682 * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
5683 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); }
5685 * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.
5686 * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat);
5689 * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME,
5690 * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName(
5691 * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ;
5693 * return Either.left(true); }
5696 private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5697 String resourceNameUpdated = updateInfoResource.getName();
5698 String resourceNameCurrent = currentResource.getName();
5699 if (!resourceNameCurrent.equals(resourceNameUpdated)) {
5700 if (!hasBeenCertified) {
5701 Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null);
5702 if (validateResourceNameResponse.isRight()) {
5703 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
5704 return Either.right(errorResponse);
5706 validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
5707 if (validateResourceNameResponse.isRight()) {
5708 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
5709 return Either.right(errorResponse);
5711 currentResource.setName(resourceNameUpdated);
5712 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5713 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5716 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
5717 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5718 return Either.right(errorResponse);
5721 return Either.left(true);
5724 private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5725 String iconUpdated = updateInfoResource.getIcon();
5726 String iconCurrent = currentResource.getIcon();
5727 if (!iconCurrent.equals(iconUpdated)) {
5728 if (!hasBeenCertified) {
5729 Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
5730 if (validateIcon.isRight()) {
5731 ResponseFormat errorResponse = validateIcon.right().value();
5732 return Either.right(errorResponse);
5735 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5736 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5737 return Either.right(errorResponse);
5740 return Either.left(true);
5743 private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5744 String vendorNameUpdated = updateInfoResource.getVendorName();
5745 String vendorNameCurrent = currentResource.getVendorName();
5746 if (!vendorNameCurrent.equals(vendorNameUpdated)) {
5747 if (!hasBeenCertified) {
5748 Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
5749 if (validateVendorName.isRight()) {
5750 ResponseFormat errorResponse = validateVendorName.right().value();
5751 return Either.right(errorResponse);
5754 log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated);
5755 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
5756 return Either.right(errorResponse);
5759 return Either.left(true);
5762 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
5763 Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
5764 if (validateCategoryName.isRight()) {
5765 ResponseFormat errorResponse = validateCategoryName.right().value();
5766 return Either.right(errorResponse);
5768 if (hasBeenCertified) {
5769 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
5770 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
5771 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
5772 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
5773 if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
5774 log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
5775 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5776 return Either.right(errorResponse);
5779 return Either.left(true);
5782 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5784 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5785 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5786 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
5787 log.trace("Update normative types");
5788 return Either.left(true);
5791 String derivedFromCurrent = currentDerivedFrom.get(0);
5792 String derivedFromUpdated = updatedDerivedFrom.get(0);
5794 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5795 if (!hasBeenCertified) {
5796 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
5797 if (validateDerivedFromExistsEither.isRight()) {
5798 return validateDerivedFromExistsEither;
5801 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
5803 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
5804 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5805 return validateDerivedFromExtending;
5809 // For derived from, we must know whether it was actually changed,
5810 // otherwise we must do no action.
5811 // Due to changes it inflicts on data model (remove artifacts,
5812 // properties...), it's not like a flat field which can be
5813 // overwritten if not changed.
5814 // So we must indicate that derived from is not changed
5815 updateInfoResource.setDerivedFrom(null);
5817 return Either.left(true);
5820 private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5822 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
5823 return Either.left(true);
5826 // IResourceOperation resourceOperation = getResourceOperation();
5828 String templateName = resource.getDerivedFrom().get(0);
5830 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
5831 if (dataModelResponse.isRight()) {
5832 StorageOperationStatus storageStatus = dataModelResponse.right().value();
5833 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateDerivedFromExist");
5834 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5835 log.debug("request to data model failed with error: {}", storageStatus.name());
5836 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5837 log.trace("audit before sending response");
5838 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5839 return Either.right(responseFormat);
5842 else if (!dataModelResponse.left().value()) {
5843 log.info("resource template with name: {}, does not exists", templateName);
5844 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5845 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5847 return Either.right(responseFormat);
5850 return Either.left(true);
5853 // for extending inheritance US815447
5854 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
5855 // If updated resource is not deriving, should fail validation
5857 * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
5859 // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
5861 * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
5863 String currentTemplateName = currentResource.getDerivedFrom().get(0);
5864 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
5866 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5867 if (dataModelResponse.isRight()) {
5868 StorageOperationStatus storageStatus = dataModelResponse.right().value();
5869 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5870 log.debug("request to data model failed with error: {}", storageStatus.name());
5871 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5872 log.trace("audit before sending response");
5873 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
5874 return Either.right(responseFormat);
5877 if (!dataModelResponse.left().value()) {
5878 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
5879 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5880 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
5882 return Either.right(responseFormat);
5885 return Either.left(true);
5888 public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5889 log.debug("validate resource derivedFrom field");
5890 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
5891 log.info("derived from (template) field is missing for the resource");
5892 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5893 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5895 return Either.right(responseFormat);
5897 return Either.left(true);
5900 private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
5902 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
5903 if (resourceOperationResponse.isLeft()) {
5904 if (!resourceOperationResponse.left().value()) {
5905 return Either.left(false);
5907 log.debug("resource with name: {}, already exists", resource.getName());
5908 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5909 return Either.right(errorResponse);
5912 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5913 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
5914 return Either.right(errorResponse);
5918 * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags();
5920 * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value();
5921 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true);
5925 * private Either<Boolean, ResponseFormat> validateResourceTags(List<String> tags, String resourceName) { log.debug("validate resource tags"); boolean includesResourceName = false; int tagListSize = 0; if (tags != null && !tags.isEmpty()) { for
5926 * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
5927 * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else {
5928 * log.debug("invalid tag {}", tag); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAG)); } tagListSize += tag.length() + 1; } if (!includesResourceName) { log.debug( "tags must include resource name");
5929 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize,
5930 * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); }
5932 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); }
5935 private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5937 List<CategoryDefinition> categories = resource.getCategories();
5938 if (categories == null || categories.size() == 0) {
5939 log.debug("Resource category is empty");
5940 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5941 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5942 return Either.right(responseFormat);
5944 if (categories.size() > 1) {
5945 log.debug("Must be only one category for resource");
5946 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
5947 return Either.right(responseFormat);
5949 CategoryDefinition category = categories.get(0);
5950 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5951 if (subcategories == null || subcategories.size() == 0) {
5952 log.debug("Missinig subcategory for resource");
5953 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5954 return Either.right(responseFormat);
5956 if (subcategories.size() > 1) {
5957 log.debug("Must be only one sub ategory for resource");
5958 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5959 return Either.right(responseFormat);
5962 SubCategoryDefinition subcategory = subcategories.get(0);
5964 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5965 log.debug("Resource category is empty");
5966 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5967 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5968 return Either.right(responseFormat);
5970 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5971 log.debug("Resource category is empty");
5972 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5973 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5974 return Either.right(responseFormat);
5977 Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
5978 if (validateCategory.isRight()) {
5979 ResponseFormat responseFormat = validateCategory.right().value();
5980 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5981 return Either.right(responseFormat);
5984 return Either.left(true);
5987 private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) {
5988 if (category != null && subcategory != null) {
5989 log.debug("validating resource category {} against valid categories list", category);
5990 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5991 if (categories.isRight()) {
5992 log.debug("failed to retrive resource categories from Titan");
5993 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
5994 return Either.right(responseFormat);
5996 List<CategoryDefinition> categoryList = categories.left().value();
5997 for (CategoryDefinition cat : categoryList) {
5998 if (cat.getName().equals(category.getName())) {
5999 for (SubCategoryDefinition subcat : cat.getSubcategories()) {
6000 if (subcat.getName().equals(subcategory.getName())) {
6001 return Either.left(true);
6004 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories());
6005 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6008 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
6009 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6011 return Either.left(false);
6014 public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
6015 String vendorRelease = resource.getVendorRelease();
6017 log.debug("validate vendor relese name");
6018 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
6019 log.info("vendor relese name is missing.");
6020 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
6021 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6022 return Either.right(errorResponse);
6025 Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
6026 if (validateVendorReleaseResponse.isRight()) {
6027 ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
6028 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6030 return validateVendorReleaseResponse;
6033 public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
6034 if (vendorRelease != null) {
6035 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
6036 log.info("vendor release exceds limit.");
6037 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
6038 return Either.right(errorResponse);
6041 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
6042 log.info("vendor release is not valid.");
6043 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
6044 return Either.right(errorResponse);
6046 return Either.left(true);
6048 return Either.left(false);
6052 private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
6053 String vendorName = resource.getVendorName();
6054 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
6055 log.info("vendor name is missing.");
6056 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
6057 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6058 return Either.right(errorResponse);
6061 Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
6062 if (validateVendorNameResponse.isRight()) {
6063 ResponseFormat responseFormat = validateVendorNameResponse.right().value();
6064 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6066 return validateVendorNameResponse;
6070 private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
6071 if (vendorName != null) {
6072 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
6073 log.info("vendor name exceds limit.");
6074 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
6075 return Either.right(errorResponse);
6078 if (!ValidationUtils.validateVendorName(vendorName)) {
6079 log.info("vendor name is not valid.");
6080 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
6081 return Either.right(errorResponse);
6083 return Either.left(true);
6086 return Either.left(false);
6091 * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
6092 * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
6093 * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6095 * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
6097 * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
6098 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
6100 * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
6101 * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
6103 * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
6104 * Either.left(false); }
6108 * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
6110 * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
6111 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6113 * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
6114 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
6116 * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
6117 * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6123 * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
6125 * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
6126 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6128 * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
6129 * null); } return validateIcon;
6133 * public Either<Boolean, ResponseFormat> validateIcon(String icon) { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
6134 * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
6135 * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6140 private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
6141 String cost = resource.getCost();
6144 if (!ValidationUtils.validateCost(cost)) {
6145 log.debug("resource cost is invalid.");
6146 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6147 return Either.right(errorResponse);
6150 return Either.left(true);
6153 private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
6154 log.debug("validate licenseType");
6155 String licenseType = resource.getLicenseType();
6156 if (licenseType != null) {
6157 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
6158 if (!licenseTypes.contains(licenseType)) {
6159 log.debug("License type {} isn't configured");
6160 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6161 if (actionEnum != null) {
6162 // In update case, no audit is required
6163 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6165 return Either.right(responseFormat);
6168 return Either.left(true);
6171 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
6172 Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
6173 if (updatedResource.getDerivedFrom() != null) {
6174 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
6175 log.debug("1. Removing interface artifacts from graph");
6176 // Remove all interface artifacts of resource
6177 String resourceId = updatedResource.getUniqueId();
6178 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
6180 if (interfaces != null) {
6181 Collection<InterfaceDefinition> values = interfaces.values();
6182 for (InterfaceDefinition interfaceDefinition : values) {
6183 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
6185 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
6186 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
6187 if (operations != null) {
6188 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
6189 Operation operation = operationEntry.getValue();
6190 ArtifactDefinition implementation = operation.getImplementationArtifact();
6191 if (implementation != null) {
6192 String uniqueId = implementation.getUniqueId();
6193 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
6194 // only thing that transacts and locks here
6195 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true);
6196 if (deleteArtifactByInterface.isRight()) {
6197 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
6198 if (!inTransaction) {
6199 titanDao.rollback();
6201 return Either.right(deleteArtifactByInterface.right().value());
6204 log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
6208 log.trace("No operations found for interface type {}", interfaceType);
6212 log.debug("2. Removing properties");
6213 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
6215 if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
6216 log.debug("Failed to remove all properties of resource");
6218 titanDao.rollback();
6219 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
6223 log.debug("Derived from wasn't changed during update");
6228 return Either.left(true);
6232 /**** Auditing *******************/
6234 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
6235 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
6237 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
6239 return webApplicationContext.getBean(class1);
6242 public ICapabilityTypeOperation getCapabilityTypeOperation() {
6243 return capabilityTypeOperation;
6246 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
6247 this.capabilityTypeOperation = capabilityTypeOperation;
6250 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
6251 log.debug("validate resource properties default values");
6252 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
6253 List<PropertyDefinition> properties = resource.getProperties();
6255 String innerType = null;
6256 if (properties != null) {
6257 for (PropertyDefinition property : properties) {
6258 if (!propertyOperation.isPropertyTypeValid(property)) {
6259 log.info("Invalid type for property");
6260 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
6261 eitherResult = Either.right(responseFormat);
6265 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
6266 if (allDataTypes.isRight()) {
6267 return Either.right(allDataTypes.right().value());
6270 type = property.getType();
6271 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6272 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value());
6273 innerType = propertyInnerTypeValid.getLeft();
6274 if (!propertyInnerTypeValid.getRight().booleanValue()) {
6275 log.info("Invalid inner type for property");
6276 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
6277 eitherResult = Either.right(responseFormat);
6282 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
6283 log.info("Invalid default value for property");
6284 ResponseFormat responseFormat;
6285 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6286 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
6288 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
6290 eitherResult = Either.right(responseFormat);
6296 return eitherResult;
6300 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
6301 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
6305 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
6306 return vfComponentInstanceBusinessLogic;
6309 private String getComponentTypeForResponse(Component component) {
6310 String componentTypeForResponse = "SERVICE";
6311 if (component instanceof Resource) {
6312 componentTypeForResponse = ((Resource) component).getResourceType().name();
6314 return componentTypeForResponse;
6317 private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6319 Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
6320 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
6322 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
6323 if (eitherNodesTemlates.isLeft()) {
6324 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
6326 if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
6327 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
6328 while (nodesNameValue.hasNext()) {
6329 Entry<String, Object> groupNameValue = nodesNameValue.next();
6331 String groupName = groupNameValue.getKey();
6332 Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue());
6333 if (eitherNode.isRight()) {
6334 String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName();
6335 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6336 return Either.right(eitherNode.right().value());
6338 GroupDefinition groupDefinition = eitherNode.left().value();
6339 groups.put(groupName, groupDefinition);
6348 private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6350 Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
6351 if (inputs.isRight()) {
6352 String message = "Failed when creating inputs: for resource:" + resource.getName();
6353 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6354 Map<String, InputDefinition> resultMap = new HashMap();
6355 return Either.left(resultMap);
6359 Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
6364 private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
6366 GroupDefinition groupInfo = new GroupDefinition();
6367 groupInfo.setName(groupName);
6368 Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
6371 if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
6372 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
6374 String groupType = null;
6375 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
6376 groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
6377 groupInfo.setType(groupType);
6379 log.debug("The 'type' member is not found under group {}", groupName);
6380 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6383 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
6384 groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
6387 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
6388 Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
6389 if (members != null) {
6390 if (members instanceof List) {
6391 Map<String, String> membersLoaded = new HashMap<>();
6392 List<?> membersAsList = (List<?>) members;
6393 for (Object member : membersAsList) {
6394 membersLoaded.put(member.toString(), "");
6396 groupInfo.setMembers(membersLoaded);
6398 log.debug("The 'type' member is not found under group {}", groupName);
6399 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6404 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
6405 Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
6407 Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType);
6408 if (regResponse.isRight())
6409 return Either.right(regResponse.right().value());
6410 if (regResponse.left().value().size() > 0) {
6411 groupInfo.convertFromGroupProperties(regResponse.left().value());
6416 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6418 } catch (Exception e) {
6419 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
6420 log.debug("error when creating group, message:{}", e.getMessage(), e);
6421 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
6427 private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) {
6429 List<GroupProperty> result = new ArrayList<>();
6431 if (properties == null) {
6432 return Either.left(result);
6435 Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
6437 if (groupTypeRes.isRight()) {
6438 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupType));
6441 Map<String, PropertyDefinition> gtProperties = new HashMap<>();
6442 GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
6444 List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
6446 if (propertiesDef != null) {
6447 gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
6450 if (properties != null) {
6452 if (properties instanceof Map) {
6454 Map<String, Object> props = (Map<String, Object>) properties;
6455 for (Entry<String, Object> entry : props.entrySet()) {
6457 String propName = entry.getKey();
6458 Object value = entry.getValue();
6460 PropertyDefinition gtDefinition = gtProperties.get(propName);
6461 if (gtDefinition == null) {
6462 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType));
6465 ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
6467 String convertedValue = null;
6468 if (value != null) {
6469 if (type == null || value instanceof Map || value instanceof List) {
6470 convertedValue = gson.toJson(value);
6472 convertedValue = value.toString();
6476 GroupProperty groupProperty = new GroupProperty();
6477 groupProperty.setValue(convertedValue);
6478 groupProperty.setName(propName);
6480 log.trace("After building group property {}", groupProperty);
6482 result.add(groupProperty);
6489 return Either.left(result);
6492 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
6496 Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false);
6497 if (userValidation.isRight()) {
6498 return Either.right(userValidation.right().value());
6502 // get resource from csar uuid
6503 Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
6504 if (either.isRight()) {
6505 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
6506 return Either.right(resp);
6509 return Either.left(either.left().value());
6513 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
6517 private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
6518 ResponseFormat responseFormat;
6519 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
6521 for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
6522 String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
6523 if (!defaultCapabilities.containsKey(capabilityType)) {
6524 responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
6525 return Either.right(responseFormat);
6527 CapabilityDefinition delaultCapability = defaultCapabilities.get(capabilityType).get(0);
6528 Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(delaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
6529 if (validationRes.isRight()) {
6530 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value());
6531 return Either.right(responseFormat);
6533 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
6534 validCapabilityList.add(delaultCapability);
6535 validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
6538 return Either.left(validCapabilitiesMap);
6541 private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
6542 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
6543 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
6544 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
6545 for (UploadPropInfo property : uploadedProperties) {
6546 String propertyName = property.getName().toLowerCase();
6547 String propertyType = property.getType();
6548 ComponentInstanceProperty validProperty;
6549 if (defaultProperties.containsKey(propertyName)) {
6550 if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
6551 return Either.right(propertyName);
6554 validProperty = new ComponentInstanceProperty();
6555 validProperty.setName(propertyName);
6556 if (property.getValue() != null)
6557 validProperty.setValue(property.getValue().toString());
6558 validProperty.setDescription(property.getDescription());
6559 validProperty.setPassword(property.isPassword());
6560 validProperties.add(validProperty);
6562 defaultCapability.setProperties(validProperties);
6563 return Either.left(true);
6566 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
6567 Resource resource, User user) {
6569 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
6570 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
6571 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
6574 // add all found Csar artifacts to list to upload
6575 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
6576 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
6577 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
6578 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
6579 ArtifactDefinition foundArtifact;
6581 if (!existingArtifactsToHandle.isEmpty()) {
6582 foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
6583 if (foundArtifact != null) {
6584 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
6585 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
6586 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
6587 // if current artifact already exists, but has different content, add him to the list to update
6588 artifactsToUpdate.add(currNewArtifact);
6590 // remove found artifact from the list of existing artifacts to handle, because it was already handled
6591 existingArtifactsToHandle.remove(foundArtifact);
6592 // and remove found artifact from the list to upload, because it should either be updated or be ignored
6593 artifactsToUpload.remove(currNewArtifact);
6595 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
6596 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
6597 currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
6598 AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
6599 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
6600 responseWrapper.setInnerElement(responseFormat);
6606 if (responseWrapper.isEmpty()) {
6607 existingArtifactsToHandle.stream()
6608 // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
6609 .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
6611 if (responseWrapper.isEmpty()) {
6612 if (!artifactsToUpload.isEmpty())
6613 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
6614 if (!artifactsToUpdate.isEmpty())
6615 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
6616 if (!artifactsToDelete.isEmpty())
6617 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
6619 if (!responseWrapper.isEmpty()) {
6620 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
6622 } catch (Exception e) {
6623 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
6624 responseWrapper.setInnerElement(responseFormat);
6625 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
6627 return nodeTypeArtifactsToHandleRes;
6630 private String buildNestedVfcToscaNamespace(String nodeTypeFullName) {
6632 String actualName = this.getNodeTypeActualName(nodeTypeFullName);
6633 return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + actualName;
6637 private String buildNestedVfcToscaResourceName(String vfResourceName, String nodeTypeFullName) {
6638 String toscaResourceName;
6639 String nameWithouNamespacePrefix = getNodeTypeActualName(nodeTypeFullName);
6640 if (nameWithouNamespacePrefix.startsWith(Constants.ABSTRACT)) {
6641 toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + nameWithouNamespacePrefix;
6643 toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + nameWithouNamespacePrefix;
6645 return toscaResourceName;
6648 public ICacheMangerOperation getCacheManagerOperation() {
6649 return cacheManagerOperation;
6652 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
6653 this.cacheManagerOperation = cacheManagerOperation;
6656 ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
6661 * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
6664 * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
6665 * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
6668 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
6670 // check if resource already exist
6671 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
6672 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
6675 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
6677 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
6678 if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
6679 result = createNodeTypeByImport(resource, user, isNormative, isInTransaction);
6682 StorageOperationStatus status = latestByName.right().value();
6683 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
6684 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
6685 log.debug("resource already exist {}. status={}", resource.getName(), status);
6686 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
6687 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
6688 result = Either.right(responseFormat);
6694 else if (latestByName.isLeft()) {
6695 // result = updateExistingNodeTypeByImport(resource, latestByName.left().value(), user, isNormative, needLock);
6700 StorageOperationStatus status = latestByName.right().value();
6701 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
6702 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
6703 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
6704 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
6705 result = Either.right(responseFormat);
6711 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
6712 log.debug("resource with name {} does not exist. create new resource", resource.getName());
6713 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
6714 if (response.isRight()) {
6715 return Either.right(response.right().value());
6718 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
6719 if (createResponse.isRight()) {
6720 return Either.right(createResponse.right().value());
6722 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
6723 ASDCKpiApi.countImportResourcesKPI();
6724 return Either.left(resourcePair);
6729 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
6731 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
6732 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
6734 if (resourceResultEither.isRight()) {
6735 if(resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
6736 log.debug("Failed to found resource with id {} ", resourceId);
6737 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
6740 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
6741 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
6744 Resource resource = resourceResultEither.left().value();
6745 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
6746 return Either.left(dataTransfer);