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, false);
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 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<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 GroupDefinition grDef = entry.getKey();
2204 if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
2205 for (ArtifactDefinition art : dissArtifactsInGroup) {
2206 grDef.getArtifacts().remove(art.getUniqueId());
2207 grDef.getArtifactsUuid().remove(art.getArtifactUUID());
2211 List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
2212 if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
2213 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
2216 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
2217 if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
2218 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
2221 if (!artifactsToUpdateMap.isEmpty()) {
2222 List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>();
2223 for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
2224 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
2225 GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
2227 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
2228 String prevUUID = artifact.getKey().getArtifactUUID();
2229 String prevId = artifact.getKey().getUniqueId();
2230 Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifact.getKey(), artifact.getValue(), updatedArtifacts,
2231 artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
2232 if (updateArtifactEither.isRight()) {
2233 log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
2234 resEither = Either.right(updateArtifactEither.right().value());
2237 ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
2238 if ( !prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId()) ){
2239 groupToUpdate.getArtifacts().remove(prevId);
2240 groupToUpdate.getArtifactsUuid().remove(prevUUID);
2241 groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
2242 groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
2248 List<GroupDefinition> associateArtifactGroup = new ArrayList<GroupDefinition>();
2250 for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
2251 List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
2252 Set<String> arifactsUids = new HashSet<String>();
2253 for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
2259 boolean isCreate = true;
2260 for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
2261 if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
2262 arifactsUids.add(createdArtifact.getUniqueId());
2264 String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
2265 if (!heatEnvId.isEmpty()) {
2266 arifactsUids.add(heatEnvId);
2267 Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
2268 if (op.isPresent()) {
2269 this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
2278 if (isCreate) { // check if already created
2279 for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
2280 if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
2281 arifactsUids.add(createdNewArtifact.getUniqueId());
2283 String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
2284 if (!heatEnvId.isEmpty()) {
2285 arifactsUids.add(heatEnvId);
2293 Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
2294 if (createArtifactEither.isRight()) {
2295 resEither = Either.right(createArtifactEither.right().value());
2298 ArtifactDefinition createdArtifact = createArtifactEither.left().value();
2299 arifactsUids.add(createdArtifact.getUniqueId());
2300 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
2301 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2302 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2303 resource.getName(), user, resource, null);
2304 if (createHeatEnvPlaceHolder.isRight()) {
2305 return Either.right(createHeatEnvPlaceHolder.right().value());
2307 String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
2308 arifactsUids.add(heatEnvId);
2313 if (arifactsUids.size() > 0) {
2314 List<String> artifactsToAssociate = new ArrayList<String>();
2315 artifactsToAssociate.addAll(arifactsUids);
2316 GroupDefinition assotiateGroup = new GroupDefinition();
2317 assotiateGroup.setUniqueId(associateEntry.getKey().getUniqueId());
2318 assotiateGroup.setArtifacts(artifactsToAssociate);
2319 associateArtifactGroup.add(assotiateGroup);
2325 * if (!associateArtifactGroup.isEmpty()) {
2327 * log.debug("Try to associate artifacts to groups.");
2329 * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
2330 * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
2335 ComponentParametersView parametersView = new ComponentParametersView();
2336 parametersView.disableAll();
2337 parametersView.setIgnoreComponentInstances(false);
2338 parametersView.setIgnoreUsers(false);
2339 parametersView.setIgnoreArtifacts(false);
2340 parametersView.setIgnoreGroups(false);
2342 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2344 if (eitherGerResource.isRight()) {
2345 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2347 resEither = Either.right(responseFormat);
2351 resEither = Either.left(eitherGerResource.left().value());
2355 private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
2356 Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
2357 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
2358 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2359 Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
2360 boolean isNeedToDeleteGroup = true;
2361 List<ArtifactDefinition> listToDelete = null;
2362 for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
2363 listToDelete = createdArtifactMap.get(maserArtifact);
2364 for (ArtifactDefinition artToDelete : listToDelete) {
2365 findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
2367 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
2368 if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
2369 MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
2370 mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
2371 mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
2372 mergedgroup.put(groupListEntry.getKey(), mergedGroup);
2373 isNeedToDeleteGroup = false;
2379 if (isNeedToDeleteGroup) {
2380 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
2387 private Set<String> findArtifactsNotInGroupToDelete(List<GroupDefinition> groups, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete) {
2388 Set<String> artifactNotInGroupSet = new HashSet<String>();
2389 for (ArtifactDefinition artifact : createdDeplymentArtifactsAfterDelete) {
2390 boolean needToDelete = true;
2391 if (artifact.getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL) || artifact.getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
2393 if (groups != null) {
2394 for (GroupDefinition group : groups) {
2395 List<String> groupArtifactIds = group.getArtifacts();
2396 if (groupArtifactIds == null || groupArtifactIds.isEmpty()) {
2399 for (String groupArtifactid : groupArtifactIds) {
2400 if (groupArtifactid.equalsIgnoreCase(artifact.getUniqueId()))
2401 needToDelete = false;
2408 artifactNotInGroupSet.add(artifact.getUniqueId());
2410 return artifactNotInGroupSet;
2413 private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
2414 List<ArtifactDefinition> createdDeplymentArtifacts) {
2415 boolean isNeedToDeleteArtifact = true;
2416 String artifactType = artifact.getArtifactType();
2417 ArtifactDefinition generatedFromArt = null;
2418 if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
2419 Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
2421 generatedFromArt = op.get();
2425 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2426 Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
2427 for (ArtifactTemplateInfo template : artifactsNames) {
2428 if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
2429 isNeedToDeleteArtifact = false;
2433 if (generatedFromArt != null) {
2434 if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
2435 isNeedToDeleteArtifact = false;
2443 if (isNeedToDeleteArtifact) {
2444 artifactsToDelete.add(artifact);
2449 private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
2450 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>();
2452 for (GroupDefinition group : groups) {
2453 Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>();
2454 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
2455 List<String> artifactsList = group.getArtifacts();
2456 if (artifactsList != null && !artifactsList.isEmpty()) {
2458 ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList);
2459 if (masterArtifact != null)
2460 gupsMap.put(masterArtifact, artifacts);
2461 groupArtifact.put(group, gupsMap);
2465 return groupArtifact;
2468 private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
2470 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2471 parsedArtifactsName.add(parsedGroupTemplate);
2472 List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
2473 if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
2474 createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
2479 public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
2480 boolean shouldLock, boolean inTransaction) {
2482 log.debug("parseResourceArtifactsInfoFromFile start");
2483 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, user);
2484 if (parseResourceInfoFromYamlEither.isRight()) {
2485 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2486 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2487 return Either.right(responseFormat);
2489 log.debug("parseResourceArtifactsInfoFromFile end");
2491 log.debug("createResourceArtifacts start");
2492 Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
2493 if (respStatus.isRight()) {
2496 log.debug("createResourceArtifacts end");
2497 log.debug("getResource start");
2498 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2499 log.debug("getResource end");
2500 if (eitherGerResource.isRight()) {
2501 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2503 return Either.right(responseFormat);
2506 return Either.left(eitherGerResource.left().value());
2510 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList,
2511 List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
2512 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2513 List<GroupDefinition> createdGroups = resource.getGroups();
2514 List<GroupDefinition> heatGroups = null;
2515 if (createdGroups != null && !createdGroups.isEmpty()) {
2516 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2519 List<GroupDefinition> needToAdd = new ArrayList<>();
2520 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2521 String groupName = groupTemplateInfo.getGroupName();
2522 Set<String> artifactsGroup = new HashSet<String>();
2523 Set<String> artifactsUUIDGroup = new HashSet<String>();
2525 resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
2526 if (resStatus.isRight())
2529 Map<String, String> members = new HashMap<String, String>();
2530 associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
2532 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2533 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2535 GroupDefinition groupDefinition = new GroupDefinition();
2536 groupDefinition.setName(groupName);
2537 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2538 groupDefinition.setArtifacts(artifactsList);
2539 groupDefinition.setArtifactsUuid(artifactsUUIDList);
2541 if (!members.isEmpty())
2542 groupDefinition.setMembers(members);
2544 List<GroupProperty> properties = new ArrayList<GroupProperty>();
2545 GroupProperty prop = new GroupProperty();
2546 prop.setName(Constants.IS_BASE);
2547 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2548 properties.add(prop);
2550 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2551 createdArtifacts.addAll(createdNewArtifacts);
2552 createdArtifacts.addAll(artifactsFromResource);
2553 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2554 if (getLatestGroupTypeRes.isRight()) {
2555 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2557 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2558 groupDefinition.convertFromGroupProperties(properties);
2560 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2561 // if (createGroup.isRight())
2562 // return Either.right(createGroup.right().value());
2563 needToAdd.add(groupDefinition);
2565 ComponentParametersView componentParametersView = new ComponentParametersView();
2566 componentParametersView.disableAll();
2567 componentParametersView.setIgnoreArtifacts(false);
2568 componentParametersView.setIgnoreGroups(false);
2569 componentParametersView.setIgnoreComponentInstances(false);
2571 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2572 if (component.isRight()) {
2573 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2575 resource = component.left().value();
2577 Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, needToAdd);
2578 if (addGroups.isRight())
2579 return Either.right(addGroups.right().value());
2584 private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
2585 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
2586 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2587 String artifactFileName = artifactTemplateInfo.getFileName();
2588 String artifactUid = "";
2589 String artifactUUID = "";
2590 String artifactEnvUid = "";
2591 boolean alreadyExist = false;
2593 // check if artifacts already exist
2594 if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
2595 for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
2596 if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
2597 artifactUid = artifactFromResource.getUniqueId();
2598 artifactUUID = artifactFromResource.getArtifactUUID();
2599 if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2600 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
2601 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2602 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
2604 alreadyExist = true;
2605 artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
2612 if (!alreadyExist) {
2613 for (ArtifactDefinition createdArtifact : createdArtifacts) {
2614 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
2615 artifactUid = createdArtifact.getUniqueId();
2616 artifactUUID = createdArtifact.getArtifactUUID();
2618 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2619 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
2620 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2621 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
2623 alreadyExist = true;
2624 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
2630 // if not exist need to create
2631 if (!alreadyExist) {
2633 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
2634 if (newArtifactEither.isRight()) {
2635 resStatus = Either.right(newArtifactEither.right().value());
2638 ArtifactDefinition newArtifact = newArtifactEither.left().value();
2639 artifactUid = newArtifact.getUniqueId();
2640 artifactUUID = newArtifact.getArtifactUUID();
2641 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
2642 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2643 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2644 resource.getName(), user, resource, null);
2645 if (createHeatEnvPlaceHolder.isRight()) {
2646 return Either.right(createHeatEnvPlaceHolder.right().value());
2648 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
2652 artifactsGroup.add(artifactUid);
2653 artifactsUUIDGroup.add(artifactUUID);
2654 if (!artifactEnvUid.isEmpty()) {
2655 artifactsGroup.add(artifactEnvUid);
2658 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
2659 if (relatedArtifacts != null) {
2660 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
2661 resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
2662 if (resStatus.isRight())
2669 private Either<Resource, ResponseFormat> createResourceArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
2670 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
2672 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2674 Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
2676 for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
2677 if (groupTemplateList != null) {
2678 resStatus = createGroupDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
2679 if (resStatus.isRight())
2688 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
2689 ArtifactOperationInfo artifactOperation) {
2691 Either<Resource, ResponseFormat> resStatus = null;
2692 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2695 List<NonMetaArtifactInfo> artifactPathAndNameList =
2696 // Stream of file paths contained in csar
2697 csar.entrySet().stream()
2698 // Filter in only VF artifact path location
2699 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
2700 // Validate and add warnings
2701 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2702 // Filter in Non Warnings
2703 .filter(e -> e.isLeft())
2704 // Convert from Either to NonMetaArtifactInfo
2705 .map(e -> e.left().value())
2707 .collect(Collectors.toList());
2709 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2711 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
2712 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2713 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
2715 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, user);
2717 if (findVfCsarArtifactsToHandleRes.isRight()) {
2718 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2720 if (resStatus == null) {
2721 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2724 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2725 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
2727 Optional<ResponseFormat> optionalCreateInDBError =
2728 // Stream of artifacts to be created
2729 currArtifactOperationPair.getValue().stream()
2730 // create each artifact
2731 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2732 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
2734 // filter in only error
2735 .filter(e -> e.isRight()).
2736 // Convert the error from either to ResponseFormat
2737 map(e -> e.right().value()).
2738 // Check if an error occurred
2740 // Error found on artifact Creation
2741 if (optionalCreateInDBError.isPresent()) {
2742 resStatus = Either.right(optionalCreateInDBError.get());
2747 if (resStatus == null) {
2748 resStatus = Either.left(resource);
2750 } catch (Exception e) {
2751 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2752 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2754 CsarUtils.handleWarningMessages(collectedWarningMessages);
2759 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2761 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2762 // collect all Deployment and Informational artifacts of VF
2763 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2764 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2766 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2767 existingArtifacts.addAll(resource.getArtifacts().values());
2769 existingArtifacts = existingArtifacts.stream()
2770 // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
2771 .filter(this::isNonMetaArtifact).collect(Collectors.toList());
2773 List<String> artifactsToIgnore = new ArrayList<>();
2774 // collect IDs of Artifacts of VF which belongs to any group
2775 if (resource.getGroups() != null) {
2776 resource.getGroups().stream().forEach(g -> {
2777 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
2778 artifactsToIgnore.addAll(g.getArtifacts());
2781 existingArtifacts = existingArtifacts.stream()
2782 // filter artifacts which belongs to any group
2783 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
2784 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2787 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2788 boolean result = true;
2789 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2795 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2796 boolean result = true;
2797 if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2803 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
2804 int labelCounter, boolean shouldLock, boolean inTransaction) {
2805 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2806 List<GroupDefinition> createdGroups = resource.getGroups();
2807 List<GroupDefinition> heatGroups = null;
2808 if (createdGroups != null && !createdGroups.isEmpty()) {
2810 // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
2811 // e.getArtifacts().stream()).filter(p ->
2812 // relevantArtifactTypes.contains(p.getArtifactType()
2813 // )).collect(Collectors.toList());
2814 // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
2815 // e -> e.getProperties().stream().filter(p ->
2816 // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
2817 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2820 List<GroupDefinition> needToCreate = new ArrayList<>();
2821 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2822 String groupName = groupTemplateInfo.getGroupName();
2823 Set<String> artifactsGroup = new HashSet<String>();
2824 Set<String> artifactsUUIDGroup = new HashSet<String>();
2826 log.debug("createDeploymentArtifactsFromCsar start");
2827 resStatus = createDeploymentArtifactFromCsar(csarUUID, ARTIFACTS_PATH, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
2828 log.debug("createDeploymentArtifactsFromCsar end");
2829 if (resStatus.isRight())
2832 Map<String, String> members = new HashMap<String, String>();
2833 associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
2835 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2836 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2838 GroupDefinition groupDefinition = new GroupDefinition();
2839 groupDefinition.setName(groupName);
2840 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2841 groupDefinition.setArtifacts(artifactsList);
2842 groupDefinition.setArtifactsUuid(artifactsUUIDList);
2844 if (!members.isEmpty())
2845 groupDefinition.setMembers(members);
2846 List<GroupProperty> properties = new ArrayList<GroupProperty>();
2847 GroupProperty prop = new GroupProperty();
2848 prop.setName(Constants.IS_BASE);
2849 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2850 properties.add(prop);
2851 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2852 if (getLatestGroupTypeRes.isRight()) {
2853 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2855 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2856 groupDefinition.convertFromGroupProperties(properties);
2857 log.debug("createGroup start");
2859 // Since in these groups we handle only artifacts, then no need to
2860 // fetch component instances
2862 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2863 // log.debug("createGroup end");
2864 // if (createGroup.isRight())
2865 // return Either.right(createGroup.right().value());
2866 needToCreate.add(groupDefinition);
2869 ComponentParametersView componentParametersView = new ComponentParametersView();
2870 componentParametersView.disableAll();
2871 componentParametersView.setIgnoreUsers(false);
2872 componentParametersView.setIgnoreArtifacts(false);
2873 componentParametersView.setIgnoreGroups(false);
2875 componentParametersView.setIgnoreComponentInstances(false);
2877 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2878 if (component.isRight()) {
2879 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2882 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), user, ComponentTypeEnum.RESOURCE, needToCreate);
2883 if (createGroups.isRight()) {
2884 return Either.right(createGroups.right().value());
2890 public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
2891 Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
2892 vfModuleProperties.entrySet().forEach(p -> {
2893 GroupProperty prop = new GroupProperty();
2894 prop.setName(p.getKey());
2896 prop.setValue(p.getValue().getForBaseModule());
2897 prop.setDefaultValue(p.getValue().getForBaseModule());
2899 prop.setValue(p.getValue().getForNonBaseModule());
2900 prop.setDefaultValue(p.getValue().getForNonBaseModule());
2902 properties.add(prop);
2905 GroupProperty proplabel = new GroupProperty();
2906 proplabel.setName("vf_module_label");
2908 Matcher matcher = pattern.matcher(moduleName);
2910 if (matcher.find()) {
2911 proplabel.setValue(matcher.group(1));
2912 proplabel.setDefaultValue(matcher.group(1));
2914 proplabel.setValue(moduleName);
2915 proplabel.setDefaultValue(moduleName);
2917 properties.add(proplabel);
2919 GroupProperty propvolume = new GroupProperty();
2920 propvolume.setName("volume_group");
2921 boolean isVolume = false;
2922 for (String artifactId : artifactsInGroup) {
2923 ArtifactDefinition artifactDef = null;
2924 artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
2925 if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
2930 propvolume.setValue(String.valueOf(isVolume));
2931 propvolume.setDefaultValue(String.valueOf(isVolume));
2932 properties.add(propvolume);
2933 mergeWithGroupTypeProperties(properties, groupType.getProperties());
2937 private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
2939 Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
2940 for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
2941 if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
2942 properties.add(new GroupProperty(groupTypeProperty));
2947 private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
2948 for (ArtifactDefinition artifact : createdArtifacts) {
2949 if (artifact.getUniqueId().equals(artifactId)) {
2956 private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
2957 if (heatGroups != null && !heatGroups.isEmpty()) {
2958 for (GroupDefinition heatGroup : heatGroups) {
2959 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
2960 if (grpoupProps != null) {
2961 Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
2962 if (op.isPresent()) {
2963 GroupProperty prop = op.get();
2964 String heatFileNAme = prop.getValue();
2965 if (null == heatFileNAme || heatFileNAme.isEmpty())
2967 List<ArtifactDefinition> artifacts = new ArrayList();
2968 for (String artifactId : artifactsGroup) {
2969 Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
2970 if (opArt.isPresent()) {
2971 artifacts.add(opArt.get());
2973 if (artifactsFromResource != null) {
2974 opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
2975 if (opArt.isPresent()) {
2976 artifacts.add(opArt.get());
2980 Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
2981 if (resOp.isPresent()) {
2982 members.putAll(heatGroup.getMembers());
2991 private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(String csarUUID, String artifactPath, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
2992 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
2993 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2994 String artifactFileName = artifactTemplateInfo.getFileName();
2995 String artifactUid = "";
2996 String artifactEnvUid = "";
2997 String artifactUUID = "";
2998 boolean alreadyExist = false;
3000 // check if artifacts already exist
3001 for (ArtifactDefinition createdArtifact : createdArtifacts) {
3002 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
3003 artifactUid = createdArtifact.getUniqueId();
3004 artifactUUID = createdArtifact.getArtifactUUID();
3005 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3006 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
3007 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3008 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
3010 alreadyExist = true;
3011 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
3015 // if not exist need to create
3016 if (!alreadyExist) {
3018 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3019 if (newArtifactEither.isRight()) {
3020 resStatus = Either.right(newArtifactEither.right().value());
3023 ArtifactDefinition newArtifact = newArtifactEither.left().value();
3024 artifactUid = newArtifact.getUniqueId();
3025 artifactUUID = newArtifact.getArtifactUUID();
3027 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
3028 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3029 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
3030 resource.getName(), user, resource, null);
3031 if (createHeatEnvPlaceHolder.isRight()) {
3032 return Either.right(createHeatEnvPlaceHolder.right().value());
3034 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
3038 artifactsGroup.add(artifactUid);
3039 artifactsUUIDGroup.add(artifactUUID);
3040 if (!artifactEnvUid.isEmpty()) {
3041 artifactsGroup.add(artifactEnvUid);
3044 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3045 if (relatedArtifacts != null) {
3046 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
3047 resStatus = createDeploymentArtifactFromCsar(csarUUID, artifactPath, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3048 if (resStatus.isRight())
3055 private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
3056 String artifactEnvUid = "";
3057 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
3058 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3059 artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
3061 return artifactEnvUid;
3064 private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
3065 List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3066 final String artifactFileName = artifactTemplateInfo.getFileName();
3067 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath + artifactFileName, artifactFileName, componentsUtils);
3068 if (artifactContententStatus.isRight()) {
3069 return Either.right(artifactContententStatus.right().value());
3071 labelCounter += createdArtifacts.size();
3073 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3075 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3076 shoudLock, inTransaction);
3078 if (uploadArtifactToService.isRight())
3079 return Either.right(uploadArtifactToService.right().value());
3081 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3082 if (currentInfo.getHeatParameters() != null) {
3084 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, false);
3085 if (updateEnvEither.isRight()) {
3086 log.debug("failed to update parameters to artifact {}", artifactFileName);
3087 return Either.right(updateEnvEither.right().value());
3090 currentInfo = updateEnvEither.left().value();
3094 createdArtifacts.add(currentInfo);
3096 return Either.left(currentInfo);
3100 private Either<ArtifactDefinition, ResponseFormat> createInformationalArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, int labelCounter, boolean shoudLock,
3101 boolean inTransaction) {
3102 final String artifactFileName = artifactTemplateInfo.getFileName();
3103 String artifactPath = CsarUtils.ARTIFACTS_PATH + CsarUtils.INFORMATIONAL_ARTIFACTS + artifactFileName;
3104 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath, artifactFileName, componentsUtils);
3105 if (artifactContententStatus.isRight())
3106 return Either.right(artifactContententStatus.right().value());
3108 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3110 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3111 shoudLock, inTransaction);
3113 if (uploadArtifactToService.isRight())
3114 return Either.right(uploadArtifactToService.right().value());
3116 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3118 return Either.left(currentInfo);
3122 private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
3123 List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
3125 Either<ArtifactDefinition, ResponseFormat> resStatus = null;
3126 String artifactFileName = artifactTemplateInfo.getFileName();
3127 String artifactUid = "";
3129 // check if artifacts already exist
3130 for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
3131 if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
3132 artifactUid = updatedArtifact.getUniqueId();
3133 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3134 log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
3135 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3136 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
3139 resStatus = Either.left(updatedArtifact);
3145 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
3146 if (artifactContententStatus.isRight()) {
3147 resStatus = Either.right(artifactContententStatus.right().value());
3151 Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
3152 oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
3154 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
3155 shouldLock, inTransaction);
3157 if (uploadArtifactToService.isRight()) {
3158 resStatus = Either.right(uploadArtifactToService.right().value());
3161 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3163 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, true);
3164 if (updateEnvEither.isRight()) {
3165 log.debug("failed to update parameters to artifact {}", artifactFileName);
3166 resStatus = Either.right(updateEnvEither.right().value());
3169 // TODO evg update env time ( must be separate US for this!!!!)
3171 artifactUid = updateEnvEither.left().value().getUniqueId();
3172 updatedArtifacts.add(updateEnvEither.left().value());
3173 resStatus = Either.left(updateEnvEither.left().value());
3179 private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
3180 Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
3181 if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
3183 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
3185 if (artifactparamsStatus.isRight()) {
3186 resStatus = Either.right(artifactparamsStatus.right().value());
3189 Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
3191 * if (propsStatus.isRight()) {
3193 * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
3195 if (propsStatus.isLeft()) {
3196 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
3197 List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
3198 // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3200 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3203 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3205 paramName = heatEnvParam.getName();
3206 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3207 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3209 String updatedParamValue = heatEnvParam.getCurrentValue();
3210 if (updatedParamValue == null)
3211 updatedParamValue = heatEnvParam.getDefaultValue();
3212 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3213 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3214 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3215 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3216 resStatus = Either.right(responseFormat);
3219 currHeatParam.setCurrentValue(HeatParameterType.isValidType(currHeatParam.getType()).getConverter().convert(updatedParamValue, null, null));
3220 // newHeatEnvParams.add(currHeatParam);
3225 currentInfo.setListHeatParameters(currentHeatEnvParams);
3226 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
3227 if (updateArifactOnResource.isRight()) {
3228 log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
3229 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3231 resStatus = Either.left(updateArifactOnResource.left().value());
3236 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3237 Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
3238 if (op.isPresent()) {
3239 ArtifactDefinition artifactInfoHeatEnv = op.get();
3240 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
3241 if (updateArifactOnResource.isRight()) {
3242 log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
3243 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3250 private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
3251 // extract heat parameters
3252 String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
3253 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
3254 if (heatParameters.isRight()) {
3255 log.debug("File {} is not in expected key-value form in csar ", fileName);
3256 BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR);
3257 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
3260 return Either.left(heatParameters.left().value());
3264 private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) {
3266 Map<String, Object> json = new HashMap<String, Object>();
3267 String artifactName = artifactTemplateInfo.getFileName();
3269 json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
3270 json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
3271 json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
3273 // DE250204: There is no need to check if base64 encoding.
3275 // String encodedPayload = new String(artifactContentent);
3276 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3277 // if (!isEncoded) {
3278 String encodedPayload = Base64.encodeBase64String(artifactContentent);
3280 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3281 String displayName = artifactName;
3282 if (artifactName.lastIndexOf(".") > 0)
3283 displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
3284 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3285 String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
3286 json.put(Constants.ARTIFACT_LABEL, label);
3287 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
3288 List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3289 json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
3290 : 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()));
3294 private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
3295 List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3297 Map<String, Object> json = new HashMap<String, Object>();
3298 if (artifactId != null && !artifactId.isEmpty())
3299 json.put(Constants.ARTIFACT_ID, artifactId);
3301 json.put(Constants.ARTIFACT_NAME, artifactName);
3302 json.put(Constants.ARTIFACT_TYPE, artifactType);
3303 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3305 String encodedPayload = new String(artifactContentent);
3307 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3308 // if (!isEncoded) {
3309 log.debug("payload is encoded. perform decode");
3310 encodedPayload = Base64.encodeBase64String(artifactContentent);
3313 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3314 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3315 json.put(Constants.ARTIFACT_LABEL, label);
3316 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3317 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3318 : 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()));
3322 private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
3325 JsonObject jsonElement = new JsonObject();
3326 jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
3328 JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
3329 if (importStructureElement == null || importStructureElement.isJsonNull()) {
3330 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3331 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3332 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3335 Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>();
3336 artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
3337 if (artifactTemplateMap.isEmpty()) {
3338 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3339 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3340 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3343 Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
3344 Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>();
3345 List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
3346 for (String artifactsTypeKey : artifactsTypeKeys) {
3348 List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
3349 Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
3350 if (artifactTemplateInfoListPairStatus.isRight()) {
3351 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3352 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3353 return Either.right(artifactTemplateInfoListPairStatus.right().value());
3355 List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
3356 if (artifactTemplateInfoList == null) {
3357 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3358 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3359 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3362 allGroups.addAll(artifactTemplateInfoList);
3363 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList);
3365 int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
3366 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
3367 if (validateGroupNamesRes.isRight()) {
3368 return Either.right(validateGroupNamesRes.right().value());
3370 return Either.left(artifactsMap);
3371 } catch (Exception e) {
3372 log.debug("Artifact file is not in expected format, fileName {}", artifactFileName);
3373 log.debug("failed with exception.", e);
3374 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3375 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3380 private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) {
3381 List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>();
3382 for (Map<String, Object> o : jsonObject) {
3383 Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
3384 if (artifacttemplateInfoStatus.isRight()) {
3385 return Either.right(artifacttemplateInfoStatus.right().value());
3388 ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
3389 if (artifacttemplateInfo != null) {
3390 artifactTemplateInfoList.add(artifacttemplateInfo);
3394 return Either.left(artifactTemplateInfoList);
3397 private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock) {
3398 log.debug("createResourceInstancesRelations try to create relations ");
3399 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3400 if (uploadResInstancesMap == null) {
3401 log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
3402 BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR);
3404 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3405 return Either.right(responseFormat);
3408 if (componentInstancesList == null || componentInstancesList.isEmpty()) {
3409 log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
3410 BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3412 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3413 return Either.right(responseFormat);
3416 log.debug("Before validateAndUpdatePropertyValue");
3417 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
3418 if (allDataTypes.isRight()) {
3419 TitanOperationStatus status = allDataTypes.right().value();
3420 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
3421 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName);
3425 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
3426 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
3427 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
3428 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
3429 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
3430 Map<String, Resource> originCompMap = new HashMap<>();
3431 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
3433 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3434 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3435 ComponentInstance currentCompInstance = null;
3436 for (ComponentInstance compInstance : componentInstancesList) {
3438 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3439 currentCompInstance = compInstance;
3444 if (currentCompInstance == null) {
3445 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3446 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3447 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3448 return Either.right(responseFormat);
3450 String resourceInstanceId = currentCompInstance.getUniqueId();
3451 Resource originResource = null;
3452 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
3453 Either<Resource, StorageOperationStatus> getPropertyRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
3454 if (getPropertyRes.isRight()) {
3455 log.debug("failed to find properties of resource {} status is {}", currentCompInstance.getComponentUid(), getPropertyRes);
3456 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getPropertyRes.right().value()), yamlName);
3457 return Either.right(responseFormat);
3459 originResource = getPropertyRes.left().value();
3460 originCompMap.put(originResource.getUniqueId(), originResource);
3462 originResource = originCompMap.get(currentCompInstance.getComponentUid());
3464 if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
3465 instCapabilties.put(currentCompInstance, originResource.getCapabilities());
3466 if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
3467 instRequirements.put(currentCompInstance, originResource.getRequirements());
3468 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
3469 instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
3470 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
3471 instAttributes.put(resourceInstanceId, originResource.getAttributes());
3473 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
3474 if (addPropertiesValueToRiRes.getStatus() != 200) {
3475 return Either.right(addPropertiesValueToRiRes);
3480 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
3481 if (addPropToInst.isRight()) {
3482 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
3483 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
3484 return Either.right(responseFormat);
3487 StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(instArtifacts, resource.getUniqueId(), user);
3488 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3489 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3490 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3491 return Either.right(responseFormat);
3494 addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
3495 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3496 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3497 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3498 return Either.right(responseFormat);
3501 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
3502 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3503 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3504 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3505 return Either.right(responseFormat);
3508 ComponentParametersView parametersView = new ComponentParametersView();
3509 parametersView.disableAll();
3510 parametersView.setIgnoreComponentInstances(false);
3511 parametersView.setIgnoreComponentInstancesProperties(false);
3512 parametersView.setIgnoreCapabilities(false);
3513 parametersView.setIgnoreRequirements(false);
3515 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
3517 if (eitherGerResource.isRight()) {
3518 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
3520 return Either.right(responseFormat);
3524 resource = eitherGerResource.left().value();
3526 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3527 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3528 ComponentInstance currentCompInstance = null;
3529 for (ComponentInstance compInstance : componentInstancesList) {
3531 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3532 currentCompInstance = compInstance;
3537 if (currentCompInstance == null) {
3538 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3539 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3540 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3541 return Either.right(responseFormat);
3544 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
3545 if (addRelationToRiRes.getStatus() != 200) {
3546 return Either.right(addRelationToRiRes);
3550 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
3551 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3552 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3553 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3554 return Either.right(responseFormat);
3557 log.debug("************* in create relations, getResource start");
3559 eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3560 log.debug("************* in create relations, getResource end");
3561 if (eitherGerResource.isRight()) {
3562 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
3564 return Either.right(responseFormat);
3567 return Either.left(eitherGerResource.left().value());
3570 private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3571 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3572 long totalCreateRel = 0;
3573 long totalCreatePropVal = 0;
3575 UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
3577 ComponentInstance currentCompInstance = null;
3579 for (ComponentInstance compInstance : componentInstancesList) {
3581 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3582 currentCompInstance = compInstance;
3588 if (currentCompInstance == null) {
3589 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3590 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3591 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3592 return responseFormat;
3594 String resourceInstanceId = currentCompInstance.getUniqueId();
3596 log.debug("************* addPropertyValuesToRi start");
3597 long startAddProperty = System.currentTimeMillis();
3598 log.debug("************* addPropertyValuesToRi end");
3599 totalCreatePropVal += (System.currentTimeMillis() - startAddProperty);
3600 Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
3601 if (regMap == null) {
3602 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3603 return responseFormat;
3605 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
3607 long startAddRelation = System.currentTimeMillis();
3609 while (nodesRegValue.hasNext()) {
3610 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3612 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3613 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3614 log.debug("Going to create relation {}", uploadRegInfo.getName());
3615 String regName = uploadRegInfo.getName();
3616 String nodeCapName = uploadRegInfo.getNode();
3617 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3618 regCapRelDef.setFromNode(resourceInstanceId);
3619 log.debug("try to find available requirement {} ", regName);
3620 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
3621 if (eitherReqStatus.isRight()) {
3622 log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
3623 return eitherReqStatus.right().value();
3626 RequirementDefinition validReq = eitherReqStatus.left().value();
3627 List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
3628 if (reqAndRelationshipPairList == null)
3629 reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
3630 RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
3631 reqAndRelationshipPair.setRequirement(regName);
3632 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3633 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3634 RelationshipImpl relationship = new RelationshipImpl();
3635 relationship.setType(validReq.getCapability());
3636 reqAndRelationshipPair.setRelationships(relationship);
3638 ComponentInstance currentCapCompInstance = null;
3639 for (ComponentInstance compInstance : componentInstancesList) {
3640 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
3641 currentCapCompInstance = compInstance;
3646 if (currentCapCompInstance == null) {
3647 log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
3648 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3649 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3650 return responseFormat;
3652 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3653 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3654 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
3655 if (aviableCapForRel == null) {
3656 log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
3657 BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
3658 ErrorSeverity.ERROR);
3659 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3660 return responseFormat;
3662 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3663 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3664 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3665 reqAndRelationshipPairList.add(reqAndRelationshipPair);
3666 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3667 relations.add(regCapRelDef);
3672 totalCreateRel += (System.currentTimeMillis() - startAddRelation);
3674 return componentsUtils.getResponseFormat(ActionStatus.OK);
3677 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3678 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
3680 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3681 if (propMap != null && propMap.size() > 0) {
3682 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
3685 List<PropertyDefinition> listFromMap = originResource.getProperties();
3686 if (listFromMap == null || listFromMap.isEmpty()) {
3687 log.debug("failed to find properties ");
3688 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3689 return responseFormat;
3691 for (PropertyDefinition prop : listFromMap) {
3692 String propName = prop.getName();
3693 if (!currPropertiesMap.containsKey(propName)) {
3694 currPropertiesMap.put(propName, prop);
3697 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
3698 for (List<UploadPropInfo> propertyList : propMap.values()) {
3700 UploadPropInfo propertyInfo = propertyList.get(0);
3701 String propName = propertyInfo.getName();
3702 if (!currPropertiesMap.containsKey(propName)) {
3703 log.debug("failed to find property {} ", propName);
3704 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3705 return responseFormat;
3707 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
3708 ComponentInstanceProperty property = null;
3710 String value = null;
3711 List<GetInputValueDataDefinition> getInputs = null;
3712 boolean isValidate = true;
3713 if (propertyInfo.getValue() != null) {
3714 getInputs = propertyInfo.getGet_input();
3715 isValidate = getInputs == null || getInputs.isEmpty();
3717 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3719 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
3721 String innerType = null;
3722 property = new ComponentInstanceProperty(curPropertyDef, value, null);
3724 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
3725 if (validatevalueEiter.isRight()) {
3726 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3729 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
3730 // property.setUniqueId(uniqueId);
3731 property.setValue(validatevalueEiter.left().value());
3733 if (getInputs != null && !getInputs.isEmpty()) {
3734 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3735 for (GetInputValueDataDefinition getInput : getInputs) {
3736 List<InputDefinition> inputs = resource.getInputs();
3737 if (inputs == null || inputs.isEmpty()) {
3738 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
3739 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3742 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3743 if (!optional.isPresent()) {
3744 log.debug("Failed to find input {} ", getInput.getInputName());
3745 // @@TODO error message
3746 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3748 InputDefinition input = optional.get();
3749 getInput.setInputId(input.getUniqueId());
3750 getInputValues.add(getInput);
3752 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3753 if (getInputIndex != null) {
3754 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
3755 if (!optional.isPresent()) {
3756 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3757 // @@TODO error message
3758 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3760 InputDefinition inputIndex = optional.get();
3761 getInputIndex.setInputId(inputIndex.getUniqueId());
3762 getInputValues.add(getInputIndex);
3767 property.setGetInputValues(getInputValues);
3769 instPropList.add(property);
3770 // delete overriden property
3771 currPropertiesMap.remove(property.getName());
3773 // add rest of properties
3774 if (!currPropertiesMap.isEmpty()) {
3775 for (PropertyDefinition value : currPropertiesMap.values()) {
3776 instPropList.add(new ComponentInstanceProperty(value));
3779 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
3781 return componentsUtils.getResponseFormat(ActionStatus.OK);
3784 // US740820 Relate RIs according to capability name
3785 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3786 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
3790 return findAviableCapability(validReq, currentCapCompInstance);
3792 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
3795 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
3796 CapabilityDefinition cap = null;
3797 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3798 if (!capMap.containsKey(validReq.getCapability())) {
3801 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
3802 if (!capByName.isPresent()) {
3805 cap = capByName.get();
3807 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
3808 String leftOccurrences = cap.getLeftOccurrences();
3809 int left = Integer.parseInt(leftOccurrences);
3812 cap.setLeftOccurrences(String.valueOf(left));
3818 // TODO temporary fix - remove specific capability node validation -
3819 // String reqNode = validReq.getNode();
3820 // if (reqNode != null && !reqNode.isEmpty() &&
3821 // !cap.getCapabilitySources().contains(reqNode)) {
3824 // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
3825 // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
3826 // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
3832 private RequirementAndRelationshipPair getReqRelPair(CapabilityDefinition cap) {
3833 RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
3834 relationPair.setCapabilityUid(cap.getUniqueId());
3835 relationPair.setCapability(cap.getName());
3836 relationPair.setCapabilityOwnerId(cap.getOwnerId());
3837 return relationPair;
3840 private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
3841 CapabilityDefinition aviableCapForRel = null;
3842 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
3843 if (capMap.containsKey(validReq.getCapability())) {
3844 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
3846 for (CapabilityDefinition cap : capList) {
3847 // TODO temporary fix - remove specific capability node
3848 // String reqNode = validReq.getNode();
3849 // if (reqNode != null && !reqNode.isEmpty()) {
3850 // if (!cap.getCapabilitySources().contains(reqNode)) {
3854 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
3855 String leftOccurrences = cap.getLeftOccurrences();
3856 if (leftOccurrences == null) {
3857 leftOccurrences = cap.getMaxOccurrences();
3859 int left = Integer.parseInt(leftOccurrences);
3862 cap.setLeftOccurrences(String.valueOf(left));
3863 aviableCapForRel = cap;
3869 aviableCapForRel = cap;
3874 return aviableCapForRel;
3877 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
3878 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
3879 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
3880 RequirementDefinition validRegDef = null;
3882 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
3883 for (RequirementDefinition reqDef : entry.getValue()) {
3884 if (reqDef.getName().equals(regName)) {
3885 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3886 String leftOccurrences = reqDef.getLeftOccurrences();
3887 if (leftOccurrences == null) {
3888 leftOccurrences = reqDef.getMaxOccurrences();
3890 int left = Integer.parseInt(leftOccurrences);
3893 reqDef.setLeftOccurrences(String.valueOf(left));
3894 validRegDef = reqDef;
3900 validRegDef = reqDef;
3906 if (validRegDef != null) {
3911 for (RequirementDefinition reqDef : list) {
3912 if (reqDef.getName().equals(regName)) {
3913 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
3914 String leftOccurrences = reqDef.getLeftOccurrences();
3915 if (leftOccurrences == null) {
3916 leftOccurrences = reqDef.getMaxOccurrences();
3918 int left = Integer.parseInt(leftOccurrences);
3921 reqDef.setLeftOccurrences(String.valueOf(left));
3922 validRegDef = reqDef;
3928 validRegDef = reqDef;
3934 if (validRegDef == null) {
3935 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
3936 return Either.right(responseFormat);
3938 return Either.left(validRegDef);
3941 @SuppressWarnings("unchecked")
3942 public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user) {
3944 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
3945 Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
3946 if (toscaElementEither.isRight()) {
3947 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3948 return Either.right(responseFormat);
3951 Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource);
3952 if (createInputsEither.isRight()) {
3953 ResponseFormat responseFormat = createInputsEither.right().value();
3954 return Either.right(responseFormat);
3957 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource);
3958 if (uploadResInstancesEither.isRight()) {
3959 ResponseFormat responseFormat = uploadResInstancesEither.right().value();
3960 return Either.right(responseFormat);
3963 Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource);
3964 if (createGroupsFromYaml.isRight()) {
3965 ResponseFormat responseFormat = createGroupsFromYaml.right().value();
3966 return Either.right(responseFormat);
3969 ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
3970 parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
3971 parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
3972 parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
3974 return Either.left(parsedToscaYamlInfo);
3977 private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
3978 Map<String, Resource> nodeTypeNamespaceMap) {
3980 Either<Resource, ResponseFormat> eitherResource = null;
3981 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
3982 if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
3983 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
3985 return Either.right(responseFormat);
3988 Map<String, Resource> existingnodeTypeMap = new HashMap<>();
3989 if (nodeTypeNamespaceMap != null && !nodeTypeNamespaceMap.isEmpty()) {
3990 nodeTypeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
3993 Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
3994 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
3995 while (nodesInfoValue.hasNext()) {
3996 log.debug("*************Going to create resource instances {}", yamlName);
3997 Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
3998 UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
4000 // updating type if the type is node type name - we need to take the
4002 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
4003 if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4004 uploadComponentInstanceInfo.setType(nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
4007 eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
4008 if (eitherResource.isRight()) {
4009 return eitherResource;
4011 Resource refResource = eitherResource.left().value();
4013 ComponentInstance componentInstance = new ComponentInstance();
4015 componentInstance.setComponentUid(refResource.getUniqueId());
4017 ComponentTypeEnum containerComponentType = resource.getComponentType();
4018 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
4020 if (containerNodeType.equals(NodeTypeEnum.Resource) && uploadComponentInstanceInfo.getCapabilities() != null) {
4021 Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4022 if (getValidComponentInstanceCapabilitiesRes.isRight()) {
4023 return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
4025 componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
4028 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
4029 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4030 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4031 return Either.right(responseFormat);
4033 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
4034 componentInstance.setName(uploadComponentInstanceInfo.getName());
4035 componentInstance.setIcon(origResource.getIcon());
4037 resourcesInstancesMap.put(componentInstance, origResource);
4040 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
4042 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
4043 if (status != null && status != StorageOperationStatus.OK) {
4044 log.debug("Failed to add component instances to container component {}", resource.getName());
4045 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
4046 eitherResource = Either.right(responseFormat);
4047 return eitherResource;
4052 log.debug("*************Going to get resource {}", resource.getUniqueId());
4053 ComponentParametersView parametersView = new ComponentParametersView();
4054 parametersView.disableAll();
4055 parametersView.setIgnoreComponentInstances(false);
4056 parametersView.setIgnoreUsers(false);
4057 parametersView.setIgnoreInputs(false); // inputs are read when creating
4058 // property values on instances
4059 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
4060 log.debug("*************finished to get resource {}", resource.getUniqueId());
4061 if (eitherGerResource.isRight()) {
4062 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
4064 return Either.right(responseFormat);
4068 if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
4070 log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
4071 BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty");
4072 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4073 return Either.right(responseFormat);
4077 return Either.left(eitherGerResource.left().value());
4080 private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeTypeNamespaceMap) {
4081 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4082 Resource refResource = null;
4083 if (nodeTypeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4084 refResource = nodeTypeNamespaceMap.get(uploadComponentInstanceInfo.getType());
4086 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
4087 if (findResourceEither.isRight()) {
4088 log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4089 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
4090 return Either.right(responseFormat);
4092 refResource = findResourceEither.left().value();
4093 nodeTypeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
4095 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
4096 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4097 log.debug("validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState);
4098 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
4099 return Either.right(responseFormat);
4101 ResourceTypeEnum resourceTypeEnum = refResource.getResourceType();
4102 if (resourceTypeEnum == ResourceTypeEnum.VF) {
4103 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", resourceTypeEnum);
4104 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4105 return Either.right(responseFormat);
4107 return Either.left(refResource);
4110 private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
4111 Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
4112 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
4113 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
4114 if (eitherNodesTemlates.isLeft()) {
4115 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
4117 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
4118 while (nodesNameValue.hasNext()) {
4119 Entry<String, Object> nodeNameValue = nodesNameValue.next();
4120 Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue.getValue());
4121 if (eitherNode.isRight()) {
4122 log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
4123 return Either.right(eitherNode.right().value());
4125 UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
4126 uploadComponentInstanceInfo.setName(nodeNameValue.getKey());
4127 moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
4133 if (moduleComponentInstances.isEmpty()) {
4134 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
4135 return Either.right(responseFormat);
4141 private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Object nodeTemplateJson) {
4143 UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
4144 Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
4147 if (nodeTemplateJson instanceof String) {
4148 String nodeTemplateJsonString = (String) nodeTemplateJson;
4149 nodeTemplateInfo.setType(nodeTemplateJsonString);
4150 } else if (nodeTemplateJson instanceof Map) {
4151 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJson;
4153 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4154 nodeTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4157 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4158 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4159 if (regResponse.isRight())
4160 return Either.right(regResponse.right().value());
4161 if (regResponse.left().value().size() > 0) {
4162 nodeTemplateInfo.setRequirements(regResponse.left().value());
4166 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4167 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4168 if (eitherCapRes.isRight())
4169 return Either.right(eitherCapRes.right().value());
4170 if (eitherCapRes.left().value().size() > 0) {
4171 nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
4174 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4175 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4176 if (regResponse.isRight())
4177 return Either.right(regResponse.right().value());
4178 if (regResponse.left().value().size() > 0) {
4179 nodeTemplateInfo.setProperties(regResponse.left().value());
4184 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
4187 } catch (Exception e) {
4188 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create capability");
4189 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
4190 log.debug("error when creating capability, message:{}", e.getMessage(), e);
4191 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
4197 private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
4198 Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
4199 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
4200 Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
4201 if (toscaProperties.isLeft()) {
4202 Map<String, Object> jsonProperties = toscaProperties.left().value();
4203 for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
4205 String propName = jsonPropObj.getKey();
4206 Object propValue = jsonPropObj.getValue();
4208 if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
4209 log.debug("Ignore property value {}.", propName);
4213 if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
4214 log.debug("Ignore property value {}.", propName);
4217 if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
4218 log.debug("Ignore property value {}.", propName);
4222 if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
4223 log.debug("Ignore property value {}.", propName);
4227 UploadPropInfo propertyDef = new UploadPropInfo();
4228 propertyDef.setValue(propValue);
4229 propertyDef.setName(propName);
4230 if (propValue instanceof Map) {
4231 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4232 propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
4235 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
4236 || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4237 createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
4240 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
4241 propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
4243 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
4244 propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
4246 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
4247 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
4249 propertyDef.setValue(propValue);
4251 } else if (propValue instanceof List) {
4252 List<Object> propValueList = (List<Object>) propValue;
4254 createInputPropList(propertyDef, propValueList);
4255 propertyDef.setValue(propValue);
4258 if (moduleProp.containsKey(propName)) {
4259 moduleProp.get(propName).add(propertyDef);
4261 List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
4262 list.add(propertyDef);
4263 moduleProp.put(propName, list);
4270 private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
4271 for (Object objValue : propValueList) {
4273 if (objValue instanceof Map) {
4274 Map<String, Object> objMap = (Map<String, Object>) objValue;
4275 if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
4276 createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
4278 Set<String> keys = objMap.keySet();
4279 for (String key : keys) {
4280 Object value = objMap.get(key);
4281 if (value instanceof Map) {
4282 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4284 } else if (value instanceof List) {
4285 List<Object> propSubValueList = (List<Object>) value;
4287 createInputPropList(propertyDef, propSubValueList);
4293 } else if (objValue instanceof List) {
4294 List<Object> propSubValueList = (List<Object>) objValue;
4296 createInputPropList(propertyDef, propSubValueList);
4303 private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
4305 if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4306 Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4307 GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
4308 List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
4309 if (getInputs == null) {
4310 getInputs = new ArrayList<GetInputValueDataDefinition>();
4312 if (getInput instanceof String) {
4314 getInputInfo.setInputName((String) getInput);
4315 getInputInfo.setPropName(propName);
4317 } else if (getInput instanceof List) {
4318 List<Object> getInputList = (List<Object>) getInput;
4319 getInputInfo.setPropName(propName);
4320 getInputInfo.setInputName((String) getInputList.get(0));
4321 if (getInputList.size() > 1) {
4322 Object indexObj = getInputList.get(1);
4323 if (indexObj instanceof Integer) {
4324 getInputInfo.setIndexValue((Integer) indexObj);
4325 } else if (indexObj instanceof Float) {
4326 int index = ((Float) indexObj).intValue();
4327 getInputInfo.setIndexValue(index);
4328 } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4329 Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4330 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
4331 getInputInfoIndex.setInputName((String) index);
4332 getInputInfoIndex.setPropName(propName);
4333 getInputInfo.setGetInputIndex(getInputInfoIndex);
4335 getInputInfo.setList(true);
4339 getInputs.add(getInputInfo);
4340 propertyDef.setGet_input(getInputs);
4341 propertyDef.setValue(propValue);
4343 Set<String> keys = propValue.keySet();
4344 for (String key : keys) {
4345 Object value = propValue.get(key);
4346 if (value instanceof Map) {
4347 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4349 } else if (value instanceof List) {
4350 List<Object> valueList = (List<Object>) value;
4351 for (Object o : valueList) {
4352 if (o instanceof Map) {
4353 createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
4366 * private boolean valueContainsStrReplace(Object propValue) {
4368 * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher =
4369 * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); }
4373 * private boolean valueContainsToken(Object propValue) {
4375 * 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 =
4381 private boolean valueContainsPattern(Pattern pattern, Object propValue) {
4383 log.debug("valueContainsToken value is {}", propValue);
4384 boolean result = false;
4385 if (propValue != null) {
4386 log.debug("valueContainspattern value is {}", propValue.getClass());
4387 Matcher matcher = pattern.matcher(propValue.toString());
4388 result = matcher.find();
4395 private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4396 Map<String, List<UploadCapInfo>> moduleCap = new HashMap<String, List<UploadCapInfo>>();
4397 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
4398 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4399 if (toscaRequirements.isLeft()) {
4400 List<Object> jsonCapabilities = toscaRequirements.left().value();
4402 for (Object jsonCapObj : jsonCapabilities) {
4404 Map<String, Object> capJsonWrapper = (Map<String, Object>) jsonCapObj;
4405 String capName = capJsonWrapper.keySet().iterator().next();
4406 Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJsonWrapper.get(capName));
4407 if (eitherCap.isRight()) {
4408 log.info("error when creating Requirement:{}, for node:{}", capName, nodeTemplateInfo);
4409 return Either.right(eitherCap.right().value());
4411 UploadCapInfo requirementDef = eitherCap.left().value();
4412 requirementDef.setName(capName);
4413 if (moduleCap.containsKey(capName)) {
4414 moduleCap.get(capName).add(requirementDef);
4416 List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
4417 list.add(requirementDef);
4418 moduleCap.put(capName, list);
4429 private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4430 Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
4431 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
4432 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4433 if (toscaRequirements.isLeft()) {
4434 List<Object> jsonRequirements = toscaRequirements.left().value();
4436 for (Object jsonRequirementObj : jsonRequirements) {
4438 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
4439 String requirementName = requirementJsonWrapper.keySet().iterator().next();
4440 Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJsonWrapper.get(requirementName));
4441 if (eitherRequirement.isRight()) {
4442 log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
4443 return Either.right(eitherRequirement.right().value());
4445 UploadReqInfo requirementDef = eitherRequirement.left().value();
4446 requirementDef.setName(requirementName);
4447 if (moduleRequirements.containsKey(requirementName)) {
4448 moduleRequirements.get(requirementName).add(requirementDef);
4450 List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
4451 list.add(requirementDef);
4452 moduleRequirements.put(requirementName, list);
4462 private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
4463 UploadCapInfo capTemplateInfo = new UploadCapInfo();
4464 Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
4466 if (capObject instanceof String) {
4467 String nodeTemplateJsonString = (String) capObject;
4468 capTemplateInfo.setNode(nodeTemplateJsonString);
4469 } else if (capObject instanceof Map) {
4470 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
4472 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4473 capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4475 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4476 capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4478 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
4479 Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
4480 if (validSourceTypesRes.isLeft()) {
4481 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList()));
4484 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4485 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4486 if (regResponse.isRight())
4487 return Either.right(regResponse.right().value());
4488 if (!regResponse.left().value().isEmpty()) {
4489 List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
4490 regResponse.left().value().values().forEach(list -> properties.addAll(list));
4491 if (!properties.isEmpty())
4492 capTemplateInfo.setProperties(properties);
4500 private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
4502 UploadReqInfo regTemplateInfo = new UploadReqInfo();
4503 Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
4505 if (regObject instanceof String) {
4506 String nodeTemplateJsonString = (String) regObject;
4507 regTemplateInfo.setNode(nodeTemplateJsonString);
4508 } else if (regObject instanceof Map) {
4509 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
4511 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4512 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4514 // US740820 Relate RIs according to capability name
4515 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
4516 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
4523 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4524 Either<Resource, ResponseFormat> result = null;
4526 // resource updated with checkout. certify the resource
4527 if (resource.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
4528 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
4529 result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
4533 result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
4534 if (result.isLeft()) {
4535 resource = result.left().value();
4536 result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
4538 if (result.isLeft()) {
4539 resource = result.left().value();
4540 result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
4544 if (result == null || result.isRight()) {
4545 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
4546 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4547 if (inTransaction == false) {
4548 log.debug("operation failed. do rollback");
4549 titanDao.rollback();
4551 } else if (inTransaction == false) {
4552 log.debug("operation success. do commit");
4561 * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
4564 * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
4565 * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
4568 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
4570 // check if resource already exist
4571 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
4572 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4575 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4577 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
4578 if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
4579 result = createResourceByImport(resource, user, isNormative, isInTransaction);
4582 StorageOperationStatus status = latestByName.right().value();
4583 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
4584 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4585 log.debug("resource already exist {}. status={}", resource.getName(), status);
4586 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
4587 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4588 result = Either.right(responseFormat);
4594 else if (latestByName.isLeft()) {
4595 result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock);
4600 StorageOperationStatus status = latestByName.right().value();
4601 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
4602 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
4603 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
4604 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4605 result = Either.right(responseFormat);
4611 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
4612 log.debug("resource with name {} does not exist. create new resource", resource.getName());
4613 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
4614 if (response.isRight()) {
4615 return Either.right(response.right().value());
4617 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
4618 if (createResponse.isRight()) {
4619 return Either.right(createResponse.right().value());
4621 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
4622 ASDCKpiApi.countImportResourcesKPI();
4623 return Either.left(resourcePair);
4628 public boolean isResourceExist(String resourceName) {
4629 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
4630 return latestByName.isLeft();
4633 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock) {
4634 String lockedResourceId = oldResource.getUniqueId();
4635 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState());
4636 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4639 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import");
4640 if (lockResult.isRight()) {
4641 return Either.right(lockResult.right().value());
4645 Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false);
4646 if (prepareResourceForUpdate.isRight()) {
4647 ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
4648 log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage());
4649 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
4650 result = Either.right(prepareResourceForUpdate.right().value());
4653 oldResource = prepareResourceForUpdate.left().value();
4655 mergeOldResourceMetadataWithNew(oldResource, newResource);
4657 Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction);
4658 if (validateFieldsResponse.isRight()) {
4659 result = Either.right(validateFieldsResponse.right().value());
4663 // contact info normalization
4664 newResource.setContactId(newResource.getContactId().toLowerCase());
4665 // non-updatable fields
4666 newResource.setCreatorUserId(user.getUserId());
4667 newResource.setCreatorFullName(user.getFullName());
4668 newResource.setLastUpdaterUserId(user.getUserId());
4669 newResource.setLastUpdaterFullName(user.getFullName());
4670 newResource.setUniqueId(oldResource.getUniqueId());
4671 newResource.setVersion(oldResource.getVersion());
4672 newResource.setInvariantUUID(oldResource.getInvariantUUID());
4673 newResource.setLifecycleState(oldResource.getLifecycleState());
4674 newResource.setUUID(oldResource.getUUID());
4675 newResource.setNormalizedName(oldResource.getNormalizedName());
4676 newResource.setSystemName(oldResource.getSystemName());
4677 if (oldResource.getCsarUUID() != null) {
4678 newResource.setCsarUUID(oldResource.getCsarUUID());
4680 if (oldResource.getImportedToscaChecksum() != null) {
4681 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
4683 newResource.setAbstract(oldResource.isAbstract());
4685 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
4686 newResource.setDerivedFrom(oldResource.getDerivedFrom());
4688 // TODO rhalili: handle artifacts here (delete from old resource and
4690 // TODO rbetzer: remove after migration - in case of resources
4691 // created without tosca artifacts - add the placeholders
4692 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
4693 setToscaArtifactsPlaceHolders(newResource, user);
4695 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
4697 if (overrideResource.isRight()) {
4698 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
4699 componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
4700 result = Either.right(responseFormat);
4704 log.debug("Resource updated successfully!!!");
4705 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4706 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
4708 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
4709 result = Either.left(resourcePair);
4712 if (result == null || result.isRight()) {
4713 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
4714 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4715 log.debug("operation failed. do rollback");
4716 titanDao.rollback();
4717 } else if (inTransaction == false) {
4718 log.debug("operation success. do commit");
4721 if (needLock == true) {
4722 log.debug("unlock resource {}", lockedResourceId);
4723 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
4730 * Merge old resource with new. Keep old category and vendor name without change
4732 * @param oldResource
4733 * @param newResource
4735 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
4737 // keep old category and vendor name without change
4738 // merge the rest of the resource metadata
4739 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
4740 newResource.setTags(oldResource.getTags());
4743 if (newResource.getDescription() == null) {
4744 newResource.setDescription(oldResource.getDescription());
4747 if (newResource.getVendorRelease() == null) {
4748 newResource.setVendorRelease(oldResource.getVendorRelease());
4751 if (newResource.getContactId() == null) {
4752 newResource.setContactId(oldResource.getContactId());
4755 newResource.setCategories(oldResource.getCategories());
4756 newResource.setVendorName(oldResource.getVendorName());
4759 private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) {
4761 Either<Resource, ResponseFormat> result = Either.left(latestResource);
4762 // check if user can edit resource
4763 if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
4765 Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
4766 result = changeState;
4772 public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction) {
4774 Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
4775 if (eitherValidation.isRight()) {
4776 return Either.right(eitherValidation.right().value());
4779 eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
4780 if (eitherValidation.isRight()) {
4781 return Either.right(eitherValidation.right().value());
4783 eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
4784 if (eitherValidation.isRight()) {
4785 return Either.right(eitherValidation.right().value());
4787 eitherValidation = validateResourceType(user, resource, actionEnum);
4788 if (eitherValidation.isRight()) {
4789 return Either.right(eitherValidation.right().value());
4792 resource.setCreatorUserId(user.getUserId());
4793 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
4794 resource.setContactId(resource.getContactId().toLowerCase());
4795 if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
4796 resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VF.name(), resource.getSystemName()));
4799 // Generate invariant UUID - must be here and not in operation since it
4800 // should stay constant during clone
4801 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
4802 resource.setInvariantUUID(invariantUUID);
4804 return Either.left(resource);
4807 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
4808 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4809 if (resource.getResourceType() == null) {
4810 log.debug("Invalid resource type for resource");
4811 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4812 eitherResult = Either.right(errorResponse);
4813 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4815 return eitherResult;
4818 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
4819 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4820 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
4821 log.debug("validate interface lifecycle Types Exist");
4822 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
4823 while (intItr.hasNext() && eitherResult.isLeft()) {
4824 InterfaceDefinition interfaceDefinition = intItr.next();
4825 String intType = interfaceDefinition.getUniqueId();
4826 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
4827 if (eitherCapTypeFound.isRight()) {
4828 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4829 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInterfaceMissingError, "Create Resource - validateLifecycleTypesCreate", intType);
4830 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
4831 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
4832 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateLifecycleTypesCreate");
4833 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
4834 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
4837 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
4838 eitherResult = Either.right(errorResponse);
4839 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4844 return eitherResult;
4847 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
4849 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
4850 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
4851 log.debug("validate capability Types Exist - capabilities section");
4853 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
4855 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
4856 if (eitherResult.isRight()) {
4857 return Either.right(eitherResult.right().value());
4862 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
4863 log.debug("validate capability Types Exist - requirements section");
4864 for (String type : resource.getRequirements().keySet()) {
4865 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type) , actionEnum, eitherResult, type, inTransaction);
4866 if (eitherResult.isRight()) {
4867 return Either.right(eitherResult.right().value());
4872 return eitherResult;
4875 //@param typeObject- the object to which the validation is done
4876 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects , AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
4877 boolean inTransaction) {
4878 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
4879 if (eitherCapTypeFound.isRight()) {
4880 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4881 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", type);
4882 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
4883 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
4884 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
4886 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
4887 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
4888 ResponseFormat errorResponse =null;
4890 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
4892 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects );
4893 eitherResult = Either.right(errorResponse);
4894 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4896 return eitherResult;
4899 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
4900 Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
4901 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
4902 if (eitherCapTypeFound.isRight()) {
4903 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
4904 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", typeEntry.getKey());
4905 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
4906 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
4907 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
4909 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
4910 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
4911 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
4912 eitherResult = Either.right(errorResponse);
4913 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
4915 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
4916 if (capabilityTypeDefinition.getProperties() != null) {
4917 for (CapabilityDefinition capDef : typeEntry.getValue()) {
4918 List<ComponentInstanceProperty> properties = capDef.getProperties();
4919 if (properties == null || properties.isEmpty()) {
4920 properties = new ArrayList<ComponentInstanceProperty>();
4921 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4922 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
4923 properties.add(newProp);
4926 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
4927 PropertyDefinition porpFromDef = prop.getValue();
4928 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
4929 for (ComponentInstanceProperty cip : properties) {
4930 if (!cip.getName().equals(porpFromDef.getName())) {
4931 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
4932 propsToAdd.add(newProp);
4935 if (!propsToAdd.isEmpty()) {
4936 properties.addAll(propsToAdd);
4940 capDef.setProperties(properties);
4943 return eitherResult;
4946 public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
4949 // lock new resource name in order to avoid creation resource with same
4951 if (inTransaction == false) {
4952 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
4953 if (lockResult.isRight()) {
4954 ResponseFormat responseFormat = lockResult.right().value();
4955 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
4956 return Either.right(responseFormat);
4959 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
4962 if (resource.deriveFromGeneric()) {
4963 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
4964 if (genericResourceEither.isRight())
4965 return genericResourceEither;
4966 if (resource.shouldGenerateInputs())
4967 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
4970 Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
4971 if (respStatus.isLeft()) {
4972 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
4973 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
4974 ASDCKpiApi.countCreatedResourcesKPI();
4976 componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
4980 if (inTransaction == false) {
4981 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
4986 private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
4987 // validate resource name uniqueness
4988 log.debug("validate resource name");
4989 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
4990 if (eitherValidation.isRight()) {
4991 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
4992 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
4993 return Either.right(errorResponse);
4995 if (eitherValidation.left().value()) {
4996 log.debug("resource with name: {}, already exists", resource.getName());
4997 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4998 return Either.right(errorResponse);
5001 log.debug("send resource {} to dao for create", resource.getName());
5003 createArtifactsPlaceHolderData(resource, user);
5009 log.debug("enrich resource with creator, version and state");
5010 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
5011 resource.setVersion(INITIAL_VERSION);
5012 resource.setHighestVersion(true);
5013 resource.setAbstract(false);
5016 Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
5017 if (createToscaElement.isLeft()) {
5018 return Either.left(createToscaElement.left().value());
5021 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
5023 return Either.right(responseFormat);
5026 private void createArtifactsPlaceHolderData(Resource resource, User user) {
5027 // create mandatory artifacts
5029 // TODO it must be removed after that artifact uniqueId creation will be
5030 // moved to ArtifactOperation
5031 // String resourceUniqueId =
5032 // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
5033 // resource.getResourceVersion());
5035 setInformationalArtifactsPlaceHolder(resource, user);
5036 setDeploymentArtifactsPlaceHolder(resource, user);
5037 setToscaArtifactsPlaceHolders(resource, user);
5040 @SuppressWarnings("unchecked")
5042 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
5043 Resource resource = (Resource) component;
5044 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
5045 if (artifactMap == null) {
5046 artifactMap = new HashMap<String, ArtifactDefinition>();
5048 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts();
5049 if (deploymentResourceArtifacts != null) {
5050 Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
5051 while (iterator.hasNext()) {
5052 Entry<String, Object> currEntry = iterator.next();
5053 boolean shouldCreateArtifact = true;
5054 Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
5055 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
5056 if (object != null) {
5057 List<String> artifactTypes = (List<String>) object;
5058 if (!artifactTypes.contains(resource.getResourceType().name())) {
5059 shouldCreateArtifact = false;
5063 log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey());
5065 if (shouldCreateArtifact) {
5066 if (artifactsBusinessLogic != null) {
5067 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT);
5068 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
5069 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5074 resource.setDeploymentArtifacts(artifactMap);
5077 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
5078 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
5079 if (artifactMap == null) {
5080 artifactMap = new HashMap<String, ArtifactDefinition>();
5082 String resourceUniqueId = resource.getUniqueId();
5083 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
5084 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
5085 List<CategoryDefinition> categories = resource.getCategories();
5086 boolean isCreateArtifact = true;
5087 if (exludeResourceCategory != null) {
5088 String category = categories.get(0).getName();
5089 for (String exlude : exludeResourceCategory) {
5090 if (exlude.equalsIgnoreCase(category)) {
5091 isCreateArtifact = false;
5098 if (informationalResourceArtifacts != null && isCreateArtifact) {
5099 Set<String> keys = informationalResourceArtifacts.keySet();
5100 for (String informationalResourceArtifactName : keys) {
5101 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
5102 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
5103 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5107 resource.setArtifacts(artifactMap);
5117 public ResponseFormat deleteResource(String resourceId, User user) {
5118 ResponseFormat responseFormat;
5119 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5120 if (eitherCreator.isRight()) {
5121 return eitherCreator.right().value();
5124 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
5125 if (resourceStatus.isRight()) {
5126 log.debug("failed to get resource {}", resourceId);
5127 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
5130 Resource resource = resourceStatus.left().value();
5132 StorageOperationStatus result = StorageOperationStatus.OK;
5133 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
5134 if (lockResult.isRight()) {
5135 result = StorageOperationStatus.GENERAL_ERROR;
5136 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5141 result = markComponentToDelete(resource);
5142 if (result.equals(StorageOperationStatus.OK)) {
5143 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5145 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5146 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5148 return responseFormat;
5151 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5152 log.warn("operation failed. do rollback");
5153 titanDao.rollback();
5155 log.debug("operation success. do commit");
5158 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
5163 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
5164 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5165 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5166 if (eitherCreator.isRight()) {
5167 return eitherCreator.right().value();
5170 // Resource resource = null;
5171 Resource resource = null;
5172 StorageOperationStatus result = StorageOperationStatus.OK;
5175 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
5176 if (resourceStatus.isRight()) {
5177 log.debug("failed to get resource {} version {}", resourceName, version);
5178 return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
5181 resource = resourceStatus.left().value();
5184 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5185 log.warn("operation failed. do rollback");
5186 titanDao.rollback();
5187 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5188 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
5190 log.debug("operation success. do commit");
5194 if (resource != null) {
5195 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
5196 if (lockResult.isRight()) {
5197 result = StorageOperationStatus.GENERAL_ERROR;
5198 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5201 result = markComponentToDelete(resource);
5202 if (!result.equals(StorageOperationStatus.OK)) {
5203 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5204 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5205 return responseFormat;
5209 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5210 log.warn("operation failed. do rollback");
5211 titanDao.rollback();
5213 log.debug("operation success. do commit");
5216 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
5219 return responseFormat;
5222 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
5225 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
5226 if (eitherCreator.isRight()) {
5227 return Either.right(eitherCreator.right().value());
5231 // IResourceOperation dataModel = getResourceOperation();
5232 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
5234 if (storageStatus.isRight()) {
5235 log.debug("failed to get resource by id {}", resourceId);
5236 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5238 return Either.left(storageStatus.left().value());
5242 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
5244 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
5245 if (resp.isRight()) {
5246 return Either.right(resp.right().value());
5249 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
5250 if (getResource.isRight()) {
5251 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
5252 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
5254 return Either.left(getResource.left().value());
5258 * updateResourceMetadata
5261 * - modifier data (userId)
5262 * @param inTransaction
5264 * @param resourceIdToUpdate
5265 * - the resource identifier
5266 * @param newResource
5268 * @return Either<Resource, responseFormat>
5270 public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
5272 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
5273 if (resp.isRight()) {
5274 return Either.right(resp.right().value());
5277 // IResourceOperation dataModel = getResourceOperation();
5278 log.debug("Get resource with id {}", resourceIdToUpdate);
5279 boolean needToUnlock = false;
5280 boolean rollbackNeeded = true;
5283 // Either<Resource, StorageOperationStatus> storageStatus =
5284 // dataModel.getResource_tx(resourceIdToUpdate, false);
5285 if (currentResource == null) {
5286 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
5287 if (storageStatus.isRight()) {
5288 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5291 currentResource = storageStatus.left().value();
5293 // verify that resource is checked-out and the user is the last
5295 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
5296 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
5300 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5301 if (!lockResult.equals(StorageOperationStatus.OK)) {
5302 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Upload Artifact - lock " + resourceIdToUpdate + ": " + NodeTypeEnum.Resource);
5303 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
5304 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
5305 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
5306 return Either.right(responseFormat);
5309 needToUnlock = true;
5311 // critical section starts here
5312 // convert json to object
5314 // Update and updated resource must have a non-empty "derivedFrom"
5316 // This code is not called from import resources, because of root
5317 // VF "derivedFrom" should be null (or ignored)
5318 if (!currentResource.getResourceType().equals(ResourceTypeEnum.VF)) {
5319 Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
5320 if (derivedFromNotEmptyEither.isRight()) {
5321 log.debug("for updated resource {}, derived from field is empty", newResource.getName());
5322 return Either.right(derivedFromNotEmptyEither.right().value());
5325 derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
5326 if (derivedFromNotEmptyEither.isRight()) {
5327 log.debug("for current resource {}, derived from field is empty", currentResource.getName());
5328 return Either.right(derivedFromNotEmptyEither.right().value());
5331 newResource.setDerivedFrom(null);
5334 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true);
5335 if (dataModelResponse.isRight()) {
5336 log.debug("failed to update resource metadata!!!");
5337 rollbackNeeded = true;
5338 return Either.right(dataModelResponse.right().value());
5341 log.debug("Resource metadata updated successfully!!!");
5342 rollbackNeeded = false;
5343 return Either.left(dataModelResponse.left().value());
5346 if (!inTransaction) {
5347 if (rollbackNeeded) {
5348 titanDao.rollback();
5355 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5360 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
5362 Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
5363 if (validateResourceFields.isRight()) {
5364 return Either.right(validateResourceFields.right().value());
5366 // Setting last updater and uniqueId
5367 newResource.setContactId(newResource.getContactId().toLowerCase());
5368 newResource.setLastUpdaterUserId(user.getUserId());
5369 newResource.setUniqueId(resourceIdToUpdate);
5370 // Cannot set highest version through UI
5371 newResource.setHighestVersion(currentResource.isHighestVersion());
5372 newResource.setCreationDate(currentResource.getCreationDate());
5374 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
5376 if (processUpdateOfDerivedFrom.isRight()) {
5377 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
5378 return Either.right(processUpdateOfDerivedFrom.right().value());
5381 log.debug("send resource {} to dao for update", newResource.getUniqueId());
5382 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
5384 if (dataModelResponse.isRight()) {
5385 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
5386 return Either.right(responseFormat);
5387 } else if (dataModelResponse.left().value() == null) {
5388 log.debug("No response from updateResource");
5389 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5391 return Either.left(dataModelResponse.left().value());
5395 * validateResourceFieldsBeforeCreate
5398 * - modifier data (userId)
5400 * - IResourceOperation for resource crud
5402 * - Resource object to validate
5403 * @return Either<Boolean, ErrorResponse>
5405 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5406 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
5407 if (componentsFieldsValidation.isRight()) {
5408 return componentsFieldsValidation;
5414 * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5416 * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5421 * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5426 * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5429 // validate category
5430 log.debug("validate category");
5431 Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
5432 if (eitherValidation.isRight()) {
5433 return eitherValidation;
5436 // validate vendor name & release
5437 log.debug("validate vendor name");
5438 eitherValidation = validateVendorName(user, resource, actionEnum);
5439 if (eitherValidation.isRight()) {
5440 return eitherValidation;
5443 log.debug("validate vendor release");
5444 eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
5445 if (eitherValidation.isRight()) {
5446 return eitherValidation;
5449 // validate contact info
5451 * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5455 log.debug("validate cost");
5456 eitherValidation = validateCost(user, resource, actionEnum);
5457 if (eitherValidation.isRight()) {
5458 return eitherValidation;
5461 // validate licenseType
5462 log.debug("validate licenseType");
5463 eitherValidation = validateLicenseType(user, resource, actionEnum);
5464 if (eitherValidation.isRight()) {
5465 return eitherValidation;
5468 // validate template (derived from)
5469 log.debug("validate derived from");
5470 if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
5471 resource.setDerivedFrom(null);
5473 eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
5474 if (eitherValidation.isRight()) {
5475 return Either.right(eitherValidation.right().value());
5478 // warn about non-updatable fields
5479 checkComponentFieldsForOverrideAttempt(resource);
5480 String currentCreatorFullName = resource.getCreatorFullName();
5481 if (currentCreatorFullName != null) {
5482 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5485 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
5486 if (currentLastUpdaterFullName != null) {
5487 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5490 Long currentLastUpdateDate = resource.getLastUpdateDate();
5491 if (currentLastUpdateDate != null) {
5492 log.warn("Resource last update date is automatically set and cannot be updated");
5495 Boolean currentAbstract = resource.isAbstract();
5496 if (currentAbstract != null) {
5497 log.warn("Resource abstract is automatically set and cannot be updated");
5500 return Either.left(true);
5504 * validateResourceFieldsBeforeUpdate
5506 * @param currentResource
5507 * - Resource object to validate
5508 * @return Either<Boolean, ErrorResponse>
5510 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
5512 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5514 // validate resource name
5515 log.debug("validate resource name before update");
5516 Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified);
5517 if (eitherValidation.isRight()) {
5518 return eitherValidation;
5521 // validate description
5522 log.debug("validate description before update");
5523 eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
5524 if (eitherValidation.isRight()) {
5525 return eitherValidation;
5528 log.debug("validate icon before update");
5529 eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
5530 if (eitherValidation.isRight()) {
5531 return eitherValidation;
5534 log.debug("validate tags before update");
5535 eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
5536 if (eitherValidation.isRight()) {
5537 return eitherValidation;
5540 log.debug("validate vendor name before update");
5541 eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
5542 if (eitherValidation.isRight()) {
5543 return eitherValidation;
5546 log.debug("validate vendor release before update");
5547 eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
5548 if (eitherValidation.isRight()) {
5549 return eitherValidation;
5552 log.debug("validate contact info before update");
5553 eitherValidation = validateContactId(null, updateInfoResource, null);
5554 if (eitherValidation.isRight()) {
5555 return eitherValidation;
5558 log.debug("validate derived before update");
5559 eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
5560 if (eitherValidation.isRight()) {
5561 return eitherValidation;
5564 log.debug("validate category before update");
5565 eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
5566 if (eitherValidation.isRight()) {
5567 return eitherValidation;
5570 // warn about non-updatable fields
5571 String currentResourceVersion = currentResource.getVersion();
5572 String updatedResourceVersion = updateInfoResource.getVersion();
5574 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
5575 log.warn("Resource version is automatically set and cannot be updated");
5578 String currentCreatorUserId = currentResource.getCreatorUserId();
5579 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
5581 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
5582 log.warn("Resource Creator UserId is automatically set and cannot be updated");
5585 String currentCreatorFullName = currentResource.getCreatorFullName();
5586 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
5588 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
5589 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5592 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
5593 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
5595 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
5596 log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
5599 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
5600 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
5602 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
5603 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5606 Long currentCreationDate = currentResource.getCreationDate();
5607 Long updatedCreationDate = updateInfoResource.getCreationDate();
5609 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
5610 log.warn("Resource Creation date is automatically set and cannot be updated");
5613 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
5614 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
5616 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
5617 log.warn("Resource last update date is automatically set and cannot be updated");
5620 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
5621 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
5623 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
5624 log.warn("Resource lifecycle state date is automatically set and cannot be updated");
5627 Boolean currentAbstract = currentResource.isAbstract();
5628 Boolean updatedAbstract = updateInfoResource.isAbstract();
5630 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
5631 log.warn("Resource abstract is automatically set and cannot be updated");
5634 Boolean currentHighestVersion = currentResource.isHighestVersion();
5635 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
5637 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
5638 log.warn("Resource highest version is automatically set and cannot be updated");
5641 String currentUuid = currentResource.getUUID();
5642 String updatedUuid = updateInfoResource.getUUID();
5644 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
5645 log.warn("Resource UUID is automatically set and cannot be updated");
5648 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
5649 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
5651 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
5652 log.warn("Resource Type cannot be updated");
5655 updateInfoResource.setResourceType(currentResource.getResourceType());
5657 String currentInvariantUuid = currentResource.getInvariantUUID();
5658 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
5660 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
5661 log.warn("Resource invariant UUID is automatically set and cannot be updated");
5662 updateInfoResource.setInvariantUUID(currentInvariantUuid);
5664 return Either.left(true);
5668 * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName();
5670 * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
5671 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); }
5673 * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.
5674 * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat);
5677 * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME,
5678 * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName(
5679 * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ;
5681 * return Either.left(true); }
5684 private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5685 String resourceNameUpdated = updateInfoResource.getName();
5686 String resourceNameCurrent = currentResource.getName();
5687 if (!resourceNameCurrent.equals(resourceNameUpdated)) {
5688 if (!hasBeenCertified) {
5689 Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null);
5690 if (validateResourceNameResponse.isRight()) {
5691 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
5692 return Either.right(errorResponse);
5694 validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
5695 if (validateResourceNameResponse.isRight()) {
5696 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
5697 return Either.right(errorResponse);
5699 currentResource.setName(resourceNameUpdated);
5700 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
5701 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
5704 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
5705 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
5706 return Either.right(errorResponse);
5709 return Either.left(true);
5712 private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5713 String iconUpdated = updateInfoResource.getIcon();
5714 String iconCurrent = currentResource.getIcon();
5715 if (!iconCurrent.equals(iconUpdated)) {
5716 if (!hasBeenCertified) {
5717 Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
5718 if (validateIcon.isRight()) {
5719 ResponseFormat errorResponse = validateIcon.right().value();
5720 return Either.right(errorResponse);
5723 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
5724 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
5725 return Either.right(errorResponse);
5728 return Either.left(true);
5731 private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5732 String vendorNameUpdated = updateInfoResource.getVendorName();
5733 String vendorNameCurrent = currentResource.getVendorName();
5734 if (!vendorNameCurrent.equals(vendorNameUpdated)) {
5735 if (!hasBeenCertified) {
5736 Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
5737 if (validateVendorName.isRight()) {
5738 ResponseFormat errorResponse = validateVendorName.right().value();
5739 return Either.right(errorResponse);
5742 log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated);
5743 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
5744 return Either.right(errorResponse);
5747 return Either.left(true);
5750 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
5751 Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
5752 if (validateCategoryName.isRight()) {
5753 ResponseFormat errorResponse = validateCategoryName.right().value();
5754 return Either.right(errorResponse);
5756 if (hasBeenCertified) {
5757 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
5758 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
5759 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
5760 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
5761 if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
5762 log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
5763 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
5764 return Either.right(errorResponse);
5767 return Either.left(true);
5770 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
5772 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
5773 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
5774 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
5775 log.trace("Update normative types");
5776 return Either.left(true);
5779 String derivedFromCurrent = currentDerivedFrom.get(0);
5780 String derivedFromUpdated = updatedDerivedFrom.get(0);
5782 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
5783 if (!hasBeenCertified) {
5784 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
5785 if (validateDerivedFromExistsEither.isRight()) {
5786 return validateDerivedFromExistsEither;
5789 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
5791 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
5792 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
5793 return validateDerivedFromExtending;
5797 // For derived from, we must know whether it was actually changed,
5798 // otherwise we must do no action.
5799 // Due to changes it inflicts on data model (remove artifacts,
5800 // properties...), it's not like a flat field which can be
5801 // overwritten if not changed.
5802 // So we must indicate that derived from is not changed
5803 updateInfoResource.setDerivedFrom(null);
5805 return Either.left(true);
5808 private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
5810 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
5811 return Either.left(true);
5814 // IResourceOperation resourceOperation = getResourceOperation();
5816 String templateName = resource.getDerivedFrom().get(0);
5818 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
5819 if (dataModelResponse.isRight()) {
5820 StorageOperationStatus storageStatus = dataModelResponse.right().value();
5821 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateDerivedFromExist");
5822 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
5823 log.debug("request to data model failed with error: {}", storageStatus.name());
5824 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
5825 log.trace("audit before sending response");
5826 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5827 return Either.right(responseFormat);
5830 else if (!dataModelResponse.left().value()) {
5831 log.info("resource template with name: {}, does not exists", templateName);
5832 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
5833 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5835 return Either.right(responseFormat);
5838 return Either.left(true);
5841 // Tal G for extending inheritance US815447
5842 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
5843 // If updated resource is not deriving, should fail validation
5845 * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
5847 // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
5849 * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
5851 String currentTemplateName = currentResource.getDerivedFrom().get(0);
5852 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
5854 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
5855 if (dataModelResponse.isRight()) {
5856 StorageOperationStatus storageStatus = dataModelResponse.right().value();
5857 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
5858 log.debug("request to data model failed with error: {}", storageStatus.name());
5859 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
5860 log.trace("audit before sending response");
5861 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
5862 return Either.right(responseFormat);
5865 if (!dataModelResponse.left().value()) {
5866 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
5867 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
5868 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
5870 return Either.right(responseFormat);
5873 return Either.left(true);
5876 public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
5877 log.debug("validate resource derivedFrom field");
5878 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
5879 log.info("derived from (template) field is missing for the resource");
5880 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
5881 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5883 return Either.right(responseFormat);
5885 return Either.left(true);
5888 private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
5890 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
5891 if (resourceOperationResponse.isLeft()) {
5892 if (!resourceOperationResponse.left().value()) {
5893 return Either.left(false);
5895 log.debug("resource with name: {}, already exists", resource.getName());
5896 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5897 return Either.right(errorResponse);
5900 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
5901 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
5902 return Either.right(errorResponse);
5906 * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags();
5908 * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value();
5909 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true);
5913 * 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
5914 * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
5915 * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else {
5916 * 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");
5917 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize,
5918 * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); }
5920 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); }
5923 private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5925 List<CategoryDefinition> categories = resource.getCategories();
5926 if (categories == null || categories.size() == 0) {
5927 log.debug("Resource category is empty");
5928 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5929 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5930 return Either.right(responseFormat);
5932 if (categories.size() > 1) {
5933 log.debug("Must be only one category for resource");
5934 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
5935 return Either.right(responseFormat);
5937 CategoryDefinition category = categories.get(0);
5938 List<SubCategoryDefinition> subcategories = category.getSubcategories();
5939 if (subcategories == null || subcategories.size() == 0) {
5940 log.debug("Missinig subcategory for resource");
5941 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
5942 return Either.right(responseFormat);
5944 if (subcategories.size() > 1) {
5945 log.debug("Must be only one sub ategory for resource");
5946 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
5947 return Either.right(responseFormat);
5950 SubCategoryDefinition subcategory = subcategories.get(0);
5952 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
5953 log.debug("Resource category is empty");
5954 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5955 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5956 return Either.right(responseFormat);
5958 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
5959 log.debug("Resource category is empty");
5960 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
5961 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5962 return Either.right(responseFormat);
5965 Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
5966 if (validateCategory.isRight()) {
5967 ResponseFormat responseFormat = validateCategory.right().value();
5968 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
5969 return Either.right(responseFormat);
5972 return Either.left(true);
5975 private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) {
5976 if (category != null && subcategory != null) {
5977 log.debug("validating resource category {} against valid categories list", category);
5978 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
5979 if (categories.isRight()) {
5980 log.debug("failed to retrive resource categories from Titan");
5981 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
5982 return Either.right(responseFormat);
5984 List<CategoryDefinition> categoryList = categories.left().value();
5985 for (CategoryDefinition cat : categoryList) {
5986 if (cat.getName().equals(category.getName())) {
5987 for (SubCategoryDefinition subcat : cat.getSubcategories()) {
5988 if (subcat.getName().equals(subcategory.getName())) {
5989 return Either.left(true);
5992 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories());
5993 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
5996 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
5997 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
5999 return Either.left(false);
6002 public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
6003 String vendorRelease = resource.getVendorRelease();
6005 log.debug("validate vendor relese name");
6006 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
6007 log.info("vendor relese name is missing.");
6008 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
6009 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6010 return Either.right(errorResponse);
6013 Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
6014 if (validateVendorReleaseResponse.isRight()) {
6015 ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
6016 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6018 return validateVendorReleaseResponse;
6021 public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
6022 if (vendorRelease != null) {
6023 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
6024 log.info("vendor release exceds limit.");
6025 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
6026 return Either.right(errorResponse);
6029 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
6030 log.info("vendor release is not valid.");
6031 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
6032 return Either.right(errorResponse);
6034 return Either.left(true);
6036 return Either.left(false);
6040 private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
6041 String vendorName = resource.getVendorName();
6042 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
6043 log.info("vendor name is missing.");
6044 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
6045 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6046 return Either.right(errorResponse);
6049 Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
6050 if (validateVendorNameResponse.isRight()) {
6051 ResponseFormat responseFormat = validateVendorNameResponse.right().value();
6052 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6054 return validateVendorNameResponse;
6058 private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
6059 if (vendorName != null) {
6060 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
6061 log.info("vendor name exceds limit.");
6062 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
6063 return Either.right(errorResponse);
6066 if (!ValidationUtils.validateVendorName(vendorName)) {
6067 log.info("vendor name is not valid.");
6068 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
6069 return Either.right(errorResponse);
6071 return Either.left(true);
6074 return Either.left(false);
6079 * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
6080 * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
6081 * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6083 * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
6085 * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
6086 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
6088 * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
6089 * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
6091 * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
6092 * Either.left(false); }
6096 * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
6098 * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
6099 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6101 * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
6102 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
6104 * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
6105 * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6111 * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
6113 * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
6114 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6116 * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
6117 * null); } return validateIcon;
6121 * 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.
6122 * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
6123 * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6128 private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
6129 String cost = resource.getCost();
6132 if (!ValidationUtils.validateCost(cost)) {
6133 log.debug("resource cost is invalid.");
6134 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6135 return Either.right(errorResponse);
6138 return Either.left(true);
6141 private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
6142 log.debug("validate licenseType");
6143 String licenseType = resource.getLicenseType();
6144 if (licenseType != null) {
6145 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
6146 if (!licenseTypes.contains(licenseType)) {
6147 log.debug("License type {} isn't configured");
6148 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6149 if (actionEnum != null) {
6150 // In update case, no audit is required
6151 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6153 return Either.right(responseFormat);
6156 return Either.left(true);
6159 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
6160 Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
6161 if (updatedResource.getDerivedFrom() != null) {
6162 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
6163 log.debug("1. Removing interface artifacts from graph");
6164 // Remove all interface artifacts of resource
6165 String resourceId = updatedResource.getUniqueId();
6166 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
6168 if (interfaces != null) {
6169 Collection<InterfaceDefinition> values = interfaces.values();
6170 for (InterfaceDefinition interfaceDefinition : values) {
6171 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
6173 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
6174 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
6175 if (operations != null) {
6176 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
6177 Operation operation = operationEntry.getValue();
6178 ArtifactDefinition implementation = operation.getImplementationArtifact();
6179 if (implementation != null) {
6180 String uniqueId = implementation.getUniqueId();
6181 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
6182 // only thing that transacts and locks here
6183 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true);
6184 if (deleteArtifactByInterface.isRight()) {
6185 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
6186 if (!inTransaction) {
6187 titanDao.rollback();
6189 return Either.right(deleteArtifactByInterface.right().value());
6192 log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
6196 log.trace("No operations found for interface type {}", interfaceType);
6200 log.debug("2. Removing properties");
6201 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
6203 if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
6204 log.debug("Failed to remove all properties of resource");
6206 titanDao.rollback();
6207 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
6211 log.debug("Derived from wasn't changed during update");
6216 return Either.left(true);
6220 /**** Auditing *******************/
6222 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
6223 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
6225 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
6227 return webApplicationContext.getBean(class1);
6230 public ICapabilityTypeOperation getCapabilityTypeOperation() {
6231 return capabilityTypeOperation;
6234 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
6235 this.capabilityTypeOperation = capabilityTypeOperation;
6238 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
6239 log.debug("validate resource properties default values");
6240 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
6241 List<PropertyDefinition> properties = resource.getProperties();
6243 String innerType = null;
6244 if (properties != null) {
6245 for (PropertyDefinition property : properties) {
6246 if (!propertyOperation.isPropertyTypeValid(property)) {
6247 log.info("Invalid type for property");
6248 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
6249 eitherResult = Either.right(responseFormat);
6253 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
6254 if (allDataTypes.isRight()) {
6255 return Either.right(allDataTypes.right().value());
6258 type = property.getType();
6259 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6260 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value());
6261 innerType = propertyInnerTypeValid.getLeft();
6262 if (!propertyInnerTypeValid.getRight().booleanValue()) {
6263 log.info("Invalid inner type for property");
6264 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
6265 eitherResult = Either.right(responseFormat);
6270 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
6271 log.info("Invalid default value for property");
6272 ResponseFormat responseFormat;
6273 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6274 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
6276 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
6278 eitherResult = Either.right(responseFormat);
6284 return eitherResult;
6288 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
6289 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
6293 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
6294 return vfComponentInstanceBusinessLogic;
6297 private String getComponentTypeForResponse(Component component) {
6298 String componentTypeForResponse = "SERVICE";
6299 if (component instanceof Resource) {
6300 componentTypeForResponse = ((Resource) component).getResourceType().name();
6302 return componentTypeForResponse;
6305 private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6307 Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
6308 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
6310 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
6311 if (eitherNodesTemlates.isLeft()) {
6312 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
6314 if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
6315 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
6316 while (nodesNameValue.hasNext()) {
6317 Entry<String, Object> groupNameValue = nodesNameValue.next();
6319 String groupName = groupNameValue.getKey();
6320 Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue());
6321 if (eitherNode.isRight()) {
6322 String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName();
6323 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6324 return Either.right(eitherNode.right().value());
6326 GroupDefinition groupDefinition = eitherNode.left().value();
6327 groups.put(groupName, groupDefinition);
6336 private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6338 Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
6339 if (inputs.isRight()) {
6340 String message = "Failed when creating inputs: for resource:" + resource.getName();
6341 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6342 Map<String, InputDefinition> resultMap = new HashMap();
6343 return Either.left(resultMap);
6347 Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
6352 private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
6354 GroupDefinition groupInfo = new GroupDefinition();
6355 groupInfo.setName(groupName);
6356 Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
6359 if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
6360 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
6362 String groupType = null;
6363 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
6364 groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
6365 groupInfo.setType(groupType);
6367 log.debug("The 'type' member is not found under group {}", groupName);
6368 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6371 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
6372 groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
6375 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
6376 Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
6377 if (members != null) {
6378 if (members instanceof List) {
6379 Map<String, String> membersLoaded = new HashMap<>();
6380 List<?> membersAsList = (List<?>) members;
6381 for (Object member : membersAsList) {
6382 membersLoaded.put(member.toString(), "");
6384 groupInfo.setMembers(membersLoaded);
6386 log.debug("The 'type' member is not found under group {}", groupName);
6387 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6392 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
6393 Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
6395 Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType);
6396 if (regResponse.isRight())
6397 return Either.right(regResponse.right().value());
6398 if (regResponse.left().value().size() > 0) {
6399 groupInfo.convertFromGroupProperties(regResponse.left().value());
6404 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6406 } catch (Exception e) {
6407 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
6408 log.debug("error when creating group, message:{}", e.getMessage(), e);
6409 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
6415 private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) {
6417 List<GroupProperty> result = new ArrayList<>();
6419 if (properties == null) {
6420 return Either.left(result);
6423 Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
6425 if (groupTypeRes.isRight()) {
6426 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupType));
6429 Map<String, PropertyDefinition> gtProperties = new HashMap<>();
6430 GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
6432 List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
6434 if (propertiesDef != null) {
6435 gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
6438 if (properties != null) {
6440 if (properties instanceof Map) {
6442 Map<String, Object> props = (Map<String, Object>) properties;
6443 for (Entry<String, Object> entry : props.entrySet()) {
6445 String propName = entry.getKey();
6446 Object value = entry.getValue();
6448 PropertyDefinition gtDefinition = gtProperties.get(propName);
6449 if (gtDefinition == null) {
6450 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType));
6453 ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
6455 String convertedValue = null;
6456 if (value != null) {
6457 if (type == null || value instanceof Map || value instanceof List) {
6458 convertedValue = gson.toJson(value);
6460 convertedValue = value.toString();
6464 GroupProperty groupProperty = new GroupProperty();
6465 groupProperty.setValue(convertedValue);
6466 groupProperty.setName(propName);
6468 log.trace("After building group property {}", groupProperty);
6470 result.add(groupProperty);
6477 return Either.left(result);
6480 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
6484 Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false);
6485 if (userValidation.isRight()) {
6486 return Either.right(userValidation.right().value());
6490 // get resource from csar uuid
6491 Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
6492 if (either.isRight()) {
6493 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
6494 return Either.right(resp);
6497 return Either.left(either.left().value());
6501 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
6505 private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
6506 ResponseFormat responseFormat;
6507 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
6509 for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
6510 String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
6511 if (!defaultCapabilities.containsKey(capabilityType)) {
6512 responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
6513 return Either.right(responseFormat);
6515 CapabilityDefinition delaultCapability = defaultCapabilities.get(capabilityType).get(0);
6516 Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(delaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
6517 if (validationRes.isRight()) {
6518 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value());
6519 return Either.right(responseFormat);
6521 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
6522 validCapabilityList.add(delaultCapability);
6523 validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
6526 return Either.left(validCapabilitiesMap);
6529 private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
6530 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
6531 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
6532 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
6533 for (UploadPropInfo property : uploadedProperties) {
6534 String propertyName = property.getName().toLowerCase();
6535 String propertyType = property.getType();
6536 ComponentInstanceProperty validProperty;
6537 if (defaultProperties.containsKey(propertyName)) {
6538 if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
6539 return Either.right(propertyName);
6542 validProperty = new ComponentInstanceProperty();
6543 validProperty.setName(propertyName);
6544 if (property.getValue() != null)
6545 validProperty.setValue(property.getValue().toString());
6546 validProperty.setDescription(property.getDescription());
6547 validProperty.setPassword(property.isPassword());
6548 validProperties.add(validProperty);
6550 defaultCapability.setProperties(validProperties);
6551 return Either.left(true);
6554 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
6555 Resource resource, User user) {
6557 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
6558 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
6559 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
6562 // add all found Csar artifacts to list to upload
6563 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
6564 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
6565 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
6566 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
6567 ArtifactDefinition foundArtifact;
6569 if (!existingArtifactsToHandle.isEmpty()) {
6570 foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
6571 if (foundArtifact != null) {
6572 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
6573 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
6574 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
6575 // if current artifact already exists, but has different content, add him to the list to update
6576 artifactsToUpdate.add(currNewArtifact);
6578 // remove found artifact from the list of existing artifacts to handle, because it was already handled
6579 existingArtifactsToHandle.remove(foundArtifact);
6580 // and remove found artifact from the list to upload, because it should either be updated or be ignored
6581 artifactsToUpload.remove(currNewArtifact);
6583 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
6584 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
6585 currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
6586 AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
6587 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
6588 responseWrapper.setInnerElement(responseFormat);
6594 if (responseWrapper.isEmpty()) {
6595 existingArtifactsToHandle.stream()
6596 // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
6597 .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
6599 if (responseWrapper.isEmpty()) {
6600 if (!artifactsToUpload.isEmpty())
6601 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
6602 if (!artifactsToUpdate.isEmpty())
6603 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
6604 if (!artifactsToDelete.isEmpty())
6605 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
6607 if (!responseWrapper.isEmpty()) {
6608 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
6610 } catch (Exception e) {
6611 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
6612 responseWrapper.setInnerElement(responseFormat);
6613 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
6615 return nodeTypeArtifactsToHandleRes;
6618 private String buildNestedVfcToscaNamespace(String nodeTypeFullName) {
6620 String actualName = this.getNodeTypeActualName(nodeTypeFullName);
6621 return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + actualName;
6625 private String buildNestedVfcToscaResourceName(String vfResourceName, String nodeTypeFullName) {
6626 String toscaResourceName;
6627 String nameWithouNamespacePrefix = getNodeTypeActualName(nodeTypeFullName);
6628 if (nameWithouNamespacePrefix.startsWith(Constants.ABSTRACT)) {
6629 toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + nameWithouNamespacePrefix;
6631 toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + nameWithouNamespacePrefix;
6633 return toscaResourceName;
6636 public ICacheMangerOperation getCacheManagerOperation() {
6637 return cacheManagerOperation;
6640 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
6641 this.cacheManagerOperation = cacheManagerOperation;
6644 ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
6649 * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
6652 * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
6653 * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
6656 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
6658 // check if resource already exist
6659 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
6660 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
6663 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
6665 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
6666 if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
6667 result = createNodeTypeByImport(resource, user, isNormative, isInTransaction);
6670 StorageOperationStatus status = latestByName.right().value();
6671 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
6672 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
6673 log.debug("resource already exist {}. status={}", resource.getName(), status);
6674 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
6675 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
6676 result = Either.right(responseFormat);
6682 else if (latestByName.isLeft()) {
6683 // result = updateExistingNodeTypeByImport(resource, latestByName.left().value(), user, isNormative, needLock);
6688 StorageOperationStatus status = latestByName.right().value();
6689 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
6690 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
6691 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
6692 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
6693 result = Either.right(responseFormat);
6699 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
6700 log.debug("resource with name {} does not exist. create new resource", resource.getName());
6701 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
6702 if (response.isRight()) {
6703 return Either.right(response.right().value());
6706 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
6707 if (createResponse.isRight()) {
6708 return Either.right(createResponse.right().value());
6710 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
6711 ASDCKpiApi.countImportResourcesKPI();
6712 return Either.left(resourcePair);
6717 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
6719 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
6720 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
6722 if (resourceResultEither.isRight()) {
6723 if(resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
6724 log.debug("Failed to found resource with id {} ", resourceId);
6725 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
6728 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
6729 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
6732 Resource resource = resourceResultEither.left().value();
6733 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
6734 return Either.left(dataTransfer);