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.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.EnumMap;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Optional;
38 import java.util.function.Function;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import java.util.stream.Collectors;
43 import javax.servlet.ServletContext;
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.collections.CollectionUtils;
47 import org.apache.commons.collections.MapUtils;
48 import org.apache.commons.lang.StringUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
51 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
52 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
53 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
54 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
55 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
56 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
57 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
60 import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.api.ActionStatus;
63 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
64 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
65 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
66 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
67 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
70 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
71 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
72 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
73 import org.openecomp.sdc.be.impl.ComponentsUtils;
74 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
75 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
76 import org.openecomp.sdc.be.info.MergedArtifactInfo;
77 import org.openecomp.sdc.be.model.ArtifactDefinition;
78 import org.openecomp.sdc.be.model.CapabilityDefinition;
79 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
80 import org.openecomp.sdc.be.model.Component;
81 import org.openecomp.sdc.be.model.ComponentInstance;
82 import org.openecomp.sdc.be.model.ComponentInstanceInput;
83 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
84 import org.openecomp.sdc.be.model.ComponentParametersView;
85 import org.openecomp.sdc.be.model.CsarInfo;
86 import org.openecomp.sdc.be.model.DataTypeDefinition;
87 import org.openecomp.sdc.be.model.GroupDefinition;
88 import org.openecomp.sdc.be.model.GroupProperty;
89 import org.openecomp.sdc.be.model.GroupTypeDefinition;
90 import org.openecomp.sdc.be.model.HeatParameterDefinition;
91 import org.openecomp.sdc.be.model.InputDefinition;
92 import org.openecomp.sdc.be.model.InterfaceDefinition;
93 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
94 import org.openecomp.sdc.be.model.LifecycleStateEnum;
95 import org.openecomp.sdc.be.model.NodeTypeInfo;
96 import org.openecomp.sdc.be.model.Operation;
97 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
98 import org.openecomp.sdc.be.model.PropertyDefinition;
99 import org.openecomp.sdc.be.model.RelationshipImpl;
100 import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
101 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
102 import org.openecomp.sdc.be.model.RequirementDefinition;
103 import org.openecomp.sdc.be.model.Resource;
104 import org.openecomp.sdc.be.model.UploadCapInfo;
105 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
106 import org.openecomp.sdc.be.model.UploadPropInfo;
107 import org.openecomp.sdc.be.model.UploadReqInfo;
108 import org.openecomp.sdc.be.model.UploadResourceInfo;
109 import org.openecomp.sdc.be.model.User;
110 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
111 import org.openecomp.sdc.be.model.category.CategoryDefinition;
112 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
113 import org.openecomp.sdc.be.model.heat.HeatParameterType;
114 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
115 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
116 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
117 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
118 import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
119 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
120 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
121 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
122 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
123 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
124 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
125 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
126 import org.openecomp.sdc.be.servlets.RepresentationUtils;
127 import org.openecomp.sdc.be.tosca.CsarUtils;
128 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
129 import org.openecomp.sdc.be.tosca.ToscaUtils;
130 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
131 import org.openecomp.sdc.be.user.IUserBusinessLogic;
132 import org.openecomp.sdc.be.user.Role;
133 import org.openecomp.sdc.be.user.UserBusinessLogic;
134 import org.openecomp.sdc.be.utils.CommonBeUtils;
135 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
136 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
137 import org.openecomp.sdc.common.api.Constants;
138 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
139 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
140 import org.openecomp.sdc.common.datastructure.Wrapper;
141 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
142 import org.openecomp.sdc.common.util.GeneralUtility;
143 import org.openecomp.sdc.common.util.ValidationUtils;
144 import org.openecomp.sdc.exception.ResponseFormat;
145 import org.slf4j.Logger;
146 import org.slf4j.LoggerFactory;
147 import org.springframework.beans.factory.annotation.Autowired;
148 import org.springframework.web.context.WebApplicationContext;
149 import org.yaml.snakeyaml.DumperOptions;
150 import org.yaml.snakeyaml.Yaml;
151 import org.yaml.snakeyaml.parser.ParserException;
153 import com.google.gson.Gson;
154 import com.google.gson.JsonElement;
155 import com.google.gson.JsonObject;
157 import fj.data.Either;
159 @org.springframework.stereotype.Component("resourceBusinessLogic")
160 public class ResourceBusinessLogic extends ComponentBusinessLogic {
162 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
163 public static final String INITIAL_VERSION = "0.1";
165 private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
166 private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
167 private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
168 private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
170 private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName());
172 private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
175 * Default constructor
177 public ResourceBusinessLogic() {
178 log.debug("ResourceBusinessLogic started");
182 private ICapabilityTypeOperation capabilityTypeOperation = null;
185 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
188 private LifecycleBusinessLogic lifecycleBusinessLogic;
191 private IPropertyOperation propertyOperation;
194 private CsarOperation csarOperation;
197 private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic;
200 private ResourceImportManager resourceImportManager;
203 private GroupBusinessLogic groupBusinessLogic;
206 private InputsBusinessLogic inputsBusinessLogic;
209 private CompositionBusinessLogic compositionBusinessLogic;
212 private ICacheMangerOperation cacheManagerOperation;
215 private ApplicationDataTypeCache dataTypeCache;
217 private Gson gson = new Gson();
219 public CsarOperation getCsarOperation() {
220 return csarOperation;
223 public void setCsarOperation(CsarOperation csarOperation) {
224 this.csarOperation = csarOperation;
227 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
228 return lifecycleBusinessLogic;
231 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
232 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
235 public IElementOperation getElementDao() {
239 public void setElementDao(IElementOperation elementDao) {
240 this.elementDao = elementDao;
243 public IUserBusinessLogic getUserAdmin() {
244 return this.userAdmin;
247 public void setUserAdmin(UserBusinessLogic userAdmin) {
248 this.userAdmin = userAdmin;
251 public ComponentsUtils getComponentsUtils() {
252 return this.componentsUtils;
255 public void setComponentsUtils(ComponentsUtils componentsUtils) {
256 this.componentsUtils = componentsUtils;
259 public ArtifactsBusinessLogic getArtifactsManager() {
260 return artifactsBusinessLogic;
263 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
264 this.artifactsBusinessLogic = artifactsManager;
267 public void setPropertyOperation(IPropertyOperation propertyOperation) {
268 this.propertyOperation = propertyOperation;
271 public ApplicationDataTypeCache getApplicationDataTypeCache() {
272 return applicationDataTypeCache;
275 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
276 this.applicationDataTypeCache = applicationDataTypeCache;
280 * 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
286 public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
287 Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
288 if (resp.isRight()) {
289 return Either.right(resp.right().value());
291 Boolean isHighest = null;
292 switch (highestFilter) {
298 case NON_HIGHEST_ONLY:
304 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
306 if (getResponse.isRight()) {
307 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
310 return Either.left(getResponse.left().value());
313 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) {
315 Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
316 if (resp.isRight()) {
317 return Either.right(resp.right().value());
320 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
324 if (dataModelResponse.isLeft()) {
325 Map<String, Boolean> result = new HashMap<>();
326 result.put("isValid", dataModelResponse.left().value());
327 log.debug("validation was successfully performed.");
328 return Either.left(result);
331 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
333 return Either.right(responseFormat);
336 public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
337 Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
338 if (createResourceResponse.isRight()) {
339 return createResourceResponse;
342 // Creating resource either by DAO or from CSAR
343 String csarUUID = null;
344 if (payloadName == null) {
345 csarUUID = resource.getCsarUUID();
347 csarUUID = payloadName;
349 if (csarUUID != null && !csarUUID.isEmpty()) {
350 // check if VF with the same Csar UUID or with he same name already
352 Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
353 if (validateCsarUuidUniquenessRes.isRight()) {
354 log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
355 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
358 Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
359 if (existingResourceRes.intValue() > 0) {
360 log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
361 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID);
362 componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null);
363 return Either.right(errorResponse);
366 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
367 createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
368 return createResourceResponse;
371 return createResourceByDao(resource, user, auditingAction, false, false, null);
374 public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
375 Either<Resource, ResponseFormat> updateResourceResponse = null;
376 Either<Resource, ResponseFormat> validateResourceResponse = null;
377 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
378 String csarUUID = null;
379 String csarVersion = null;
380 if (payloadName == null) {
381 csarUUID = resource.getCsarUUID();
382 csarVersion = resource.getCsarVersion();
384 csarUUID = payloadName;
386 if (csarUUID != null && !csarUUID.isEmpty()) {
387 Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
388 if (responseWrapper.isEmpty()) {
389 validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
391 if (responseWrapper.isEmpty()) {
392 validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
394 if (responseWrapper.isEmpty()) {
395 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
396 overrideImmutableMetadata(oldResource, resource);
398 validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
399 if (validateResourceResponse.isRight()) {
400 responseWrapper.setInnerElement(validateResourceResponse.right().value());
403 if (responseWrapper.isEmpty()) {
404 String oldCsarVersion = oldResource.getCsarVersion();
405 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId);
406 // (on boarding flow): If the update includes same csarUUID and
407 // same csarVersion as already in the VF - no need to import the
408 // csar (do only metadata changes if there are).
409 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
410 updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
412 updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
416 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
417 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName());
418 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
419 responseWrapper.setInnerElement(errorResponse);
421 if (responseWrapper.isEmpty()) {
422 return updateResourceResponse;
424 return Either.right(responseWrapper.getInnerElement());
427 private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource, Resource resource, String csarUUID, User user) {
428 // (on boarding flow): If the update includes a csarUUID: verify this
429 // csarUUID is not in use by another VF, If it is - use same error as
431 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
432 // select another or update the existing VF." %1 - csarUUID, %2 - VF
434 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
435 if (resourceLinkedToCsarRes.isRight()) {
436 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
437 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
438 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
440 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
441 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
442 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
443 responseWrapper.setInnerElement(errorResponse);
447 private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
448 // (on boarding flow): If the update includes csarUUID which is
449 // different from the csarUUID of the VF - fail with
450 // error: "Error: Resource %1 cannot be updated using since it is linked
451 // to a different VSP" %1 - VF name
452 String oldCsarUUID = oldResource.getCsarUUID();
453 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
454 log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", resourceUniqueId, csarUUID, oldCsarUUID);
455 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
456 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
457 responseWrapper.setInnerElement(errorResponse);
461 private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
462 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId);
463 if (oldResourceRes.isRight()) {
464 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
465 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
468 return oldResourceRes.left().value();
471 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
472 resource.setName(oldRresource.getName());
473 resource.setIcon(oldRresource.getIcon());
474 resource.setTags(oldRresource.getTags());
475 resource.setVendorName(oldRresource.getVendorName());
476 resource.setCategories(oldRresource.getCategories());
477 resource.setDerivedFrom(oldRresource.getDerivedFrom());
480 private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload,
484 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
485 if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
486 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", oldRresource.getLastUpdaterUserId(), user.getUserId());
487 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
490 String lockedResourceId = oldRresource.getUniqueId();
491 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
493 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
494 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
495 csar = csarUIPayload;
497 csar = csarOperation.getCsar(csarUUID, user);
499 if (csar.isRight()) {
500 log.debug("Failed to get csar for casrUUID{} ", csarUUID);
501 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
504 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, user, csarUUID, csar);
505 if (toscaYamlCsarStatus.isRight()) {
506 return Either.right(toscaYamlCsarStatus.right().value());
508 Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
509 if (checksum.isRight()) {
510 log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
511 return Either.right(checksum.right().value());
513 boolean isUpdateYaml = true;
514 if (checksum.left().value().equals(oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
515 log.debug("The checksums are equals for csarUUID {}, existing checsum is {}, new one is {} ", csarUUID, oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum.left().value());
516 if (oldRresource.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT))
517 isUpdateYaml = false;
519 oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum.left().value());
522 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource, "update Resource From Csar");
523 if (lockResult.isRight()) {
524 return Either.right(lockResult.right().value());
527 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
528 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
529 CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, true);
530 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
531 Either<Resource, ResponseFormat> result = null;
533 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, oldRresource);
534 if (findNodeTypesArtifactsToHandleRes.isRight()) {
535 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
536 result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
539 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value();
541 result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, isUpdateYaml, yamlFileName, yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null);
544 if (result == null || result.isRight()) {
545 log.warn("operation failed. do rollback");
547 if (!createdArtifacts.isEmpty()) {
548 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
549 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
550 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
551 result = Either.right(componentsUtils.getResponseFormat(actionStatus, oldRresource.getName()));
553 log.debug("component and all its artifacts were deleted, id = {}", oldRresource.getName());
556 log.debug("operation success. do commit");
559 log.debug("unlock resource {}", lockedResourceId);
560 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
566 private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts,
567 boolean isUpdateYaml, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
568 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, String nodeName) {
569 Either<Resource, ResponseFormat> result;
570 Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither;
571 boolean inTransaction = true;
572 boolean shouldLock = false;
574 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate;
575 Resource preparedResource;
576 Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName);
577 if (uploadComponentInstanceInfoMap.isRight()) {
578 ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
579 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, "", "", updateResource, null);
580 result = Either.right(responseFormat);
584 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances();
586 if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) {
588 prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock);
589 if (prepareForUpdate.isRight()) {
590 log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
591 result = Either.right(prepareForUpdate.right().value());
594 preparedResource = prepareForUpdate.left().value().left;
596 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
598 parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
599 if (parseNodeTypeInfoYamlEither.isRight()) {
600 ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
601 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
602 result = Either.right(responseFormat);
606 Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
607 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource, csarInfo.getModifier(), inputs, inTransaction);
608 if (createInputsOnResource.isRight()) {
609 log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
610 ResponseFormat responseFormat = createInputsOnResource.right().value();
611 componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
612 result = Either.right(responseFormat);
615 preparedResource = createInputsOnResource.left().value();
617 Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock, csarInfo.getCreatedNodes());
618 if (createResourcesInstancesEither.isRight()) {
619 log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
620 ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
621 componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
622 result = Either.right(responseFormat);
625 preparedResource = createResourcesInstancesEither.left().value();
627 createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
628 if (createResourcesInstancesEither.isRight()) {
629 log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
630 result = Either.right(createResourcesInstancesEither.right().value());
634 preparedResource = createResourcesInstancesEither.left().value();
636 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), preparedResource.getSystemName());
637 if (validateUpdateVfGroupNamesRes.isRight()) {
639 return Either.right(validateUpdateVfGroupNamesRes.right().value());
641 // add groups to resource
642 Map<String, GroupDefinition> groups;
644 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
645 groups = validateUpdateVfGroupNamesRes.left().value();
647 groups = uploadComponentInstanceInfoMap.left().value().getGroups();
649 Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource, csarInfo.getModifier(), groups);
650 if (updatedGroupsOnResource.isRight()) {
652 return updatedGroupsOnResource;
654 preparedResource = updatedGroupsOnResource.left().value();
657 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(oldRresource.getUniqueId(), newRresource, csarInfo.getModifier(), oldRresource, shouldLock, inTransaction);
658 if (dataModelResponse.isRight()) {
659 log.debug("failed to update resource metadata {}", dataModelResponse.right().value());
660 result = Either.right(dataModelResponse.right().value());
663 preparedResource = dataModelResponse.left().value();
666 if(preparedResource.getResourceType() == ResourceTypeEnum.CVFC){
667 if(nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()){
668 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
669 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
670 if(handleNodeTypeArtifactsRes.isRight()){
671 return Either.right(handleNodeTypeArtifactsRes.right().value());
675 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
676 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), shouldLock, inTransaction);
677 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
678 if (createdCsarArtifactsEither.isRight()) {
679 return createdCsarArtifactsEither;
681 preparedResource = createdCsarArtifactsEither.left().value();
684 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
685 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource);
690 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
692 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
693 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
694 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
697 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
698 Map<String, String> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
699 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes;
700 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
701 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarInfo.getCsarUUID());
703 for (Entry<String, String> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) {
704 String currVfcToscaName = currVfcToscaNameEntry.getValue();
705 String currNamespace = currVfcToscaNameEntry.getKey();
706 log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
708 Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
709 Resource curNodeType = null;
710 if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
711 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value());
712 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarInfo.getCsarUUID());
713 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
714 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
716 } else if (curVfcRes.isLeft()) {
717 curNodeType = curVfcRes.left().value();
719 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
720 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
721 if (extractedVfcsArtifacts.containsKey(currNamespace)) {
722 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
724 curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
725 if (curNodeTypeArtifactsToHandleRes.isRight()) {
726 nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
729 curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
731 } else if (curNodeType != null) {
732 // delete all artifacts if have not received artifacts from csar
733 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
734 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
735 // delete all informational artifacts
736 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList()));
737 // delete all deployment artifacts
738 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
739 if (!artifactsToDelete.isEmpty()) {
740 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
743 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
744 nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
747 } catch (Exception e) {
748 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
749 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
750 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
752 return nodeTypesArtifactsToHandleRes;
755 private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
757 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
758 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
759 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
761 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
762 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
763 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
764 if (curNodeType != null) {
765 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
766 if (curNodeType.getDeploymentArtifacts() != null) {
767 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
769 if (curNodeType.getArtifacts() != null) {
770 existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
772 for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
773 ArtifactDefinition foundArtifact;
775 if (!existingArtifacts.isEmpty()) {
776 foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
777 if (foundArtifact != null) {
778 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
779 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
780 foundArtifact.setPayload(currNewArtifact.getPayloadData());
781 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
782 foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
783 artifactsToUpdate.add(foundArtifact);
785 existingArtifacts.remove(foundArtifact.getArtifactLabel());
786 artifactsToUpload.remove(currNewArtifact);
788 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
789 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
790 foundArtifact.getArtifactType());
791 responseWrapper.setInnerElement(responseFormat);
797 if (responseWrapper.isEmpty()) {
798 artifactsToDelete.addAll(existingArtifacts.values());
801 if (responseWrapper.isEmpty()) {
802 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
803 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
804 if (!artifactsToUpload.isEmpty())
805 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
806 if (!artifactsToUpdate.isEmpty())
807 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
808 if (!artifactsToDelete.isEmpty())
809 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
811 nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
813 if (!responseWrapper.isEmpty()) {
814 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
816 } catch (Exception e) {
817 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
818 responseWrapper.setInnerElement(responseFormat);
819 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
821 return nodeTypeArtifactsToHandleRes;
825 * Changes resource life cycle state to checked out
829 * @param inTransaction
832 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
833 Either<Resource, ResponseFormat> checkoutResourceRes;
835 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
836 log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
837 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
838 new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
839 if (checkoutRes.isRight()) {
840 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
841 checkoutResourceRes = Either.right(checkoutRes.right().value());
843 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
846 checkoutResourceRes = Either.left(resource);
848 } catch (Exception e) {
849 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
850 checkoutResourceRes = Either.right(responseFormat);
851 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
853 return checkoutResourceRes;
857 * Handles Artifacts of NodeType
859 * @param nodeTypeResource
860 * @param nodeTypeArtifactsToHandle
861 * @param vfcsNewCreatedArtifacts
863 * @param inTransaction
866 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> createdArtifacts,
867 User user, boolean inTransaction, boolean ignoreLifecycleState) {
868 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
869 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
870 Either<Resource, ResponseFormat> changeStateResponse;
872 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
873 if (changeStateResponse.isRight()) {
874 return Either.right(changeStateResponse.right().value());
876 nodeTypeResource = changeStateResponse.left().value();
878 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
879 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
880 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
881 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
882 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
883 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
884 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
885 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
886 artifactsBusinessLogic.new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
887 if (handleNodeTypeArtifactsRequestRes.isRight()) {
888 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
891 if (curOperation == ArtifactOperationEnum.Create) {
892 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
894 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
897 if (handleNodeTypeArtifactsRes == null) {
898 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
900 } catch (Exception e) {
901 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
902 handleNodeTypeArtifactsRes = Either.right(responseFormat);
903 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
905 return handleNodeTypeArtifactsRes;
908 private Map<String, String> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName, CsarInfo csarInfo) {
909 Map<String, String> vfcToscaNames = new HashMap<>();
911 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
912 if (!nodes.isEmpty()) {
913 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
914 while (nodesNameEntry.hasNext()) {
915 Entry<String, Object> nodeType = nodesNameEntry.next();
916 String toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
917 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
920 return vfcToscaNames;
923 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
924 Map<String, Object> nodes = new HashMap<>();
925 for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){
926 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
928 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
932 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
933 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
934 if (eitherNodeTypes.isLeft()) {
935 nodes.putAll(eitherNodeTypes.left().value());
939 public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
940 log.trace("************* created successfully from YAML, resource TOSCA ");
942 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
943 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
944 csar = csarUIPayload;
946 csar = csarOperation.getCsar(csarUUID, user);
949 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar);
950 if (toscaYamlCsarStatus.isRight()) {
951 return Either.right(toscaYamlCsarStatus.right().value());
953 Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
954 if (toscaYamlChecksum.isRight()) {
955 log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, toscaYamlChecksum.right().value());
956 return Either.right(toscaYamlChecksum.right().value());
958 resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value());
960 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
961 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
962 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
964 CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, false);
965 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
966 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, resource);
967 if (findNodeTypesArtifactsToHandleRes.isRight()) {
968 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
969 return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
971 Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
972 if (createResourceFromYaml.isRight()) {
973 log.debug("Couldn't create resource from YAML");
974 return Either.right(createResourceFromYaml.right().value());
977 Resource vfResource = createResourceFromYaml.left().value();
978 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
979 return Either.left(vfResource);
982 private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) {
983 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
984 List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
985 for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) {
986 extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry);
988 if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
989 setDerivedFrom(nodeTypesInfo, globalSubstitutes);
991 markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo);
992 return nodeTypesInfo;
995 @SuppressWarnings("unchecked")
996 private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo, List<Entry<String, byte[]>> globalSubstitutes) {
997 for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
998 String yamlFileContents = new String(entry.getValue());
999 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1000 Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
1001 if (nodeTypesEither.isLeft()) {
1002 Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
1003 for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
1004 Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
1005 if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
1006 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1007 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
1008 List<String> derivedFrom = new ArrayList<>();
1009 derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
1010 nodeTypeInfo.setDerivedFrom(derivedFrom);
1018 @SuppressWarnings("unchecked")
1019 private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
1020 List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) {
1021 if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
1022 if (!isGlobalSubstitute(entry.getKey())) {
1023 String yamlFileContents = new String(entry.getValue());
1024 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1025 Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
1026 if (substitutionMappingsEither.isLeft()) {
1027 Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value();
1028 if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
1029 NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
1030 nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
1031 nodeTypeInfo.setTemplateFileName(entry.getKey());
1032 nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
1033 nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
1037 globalSubstitutes.add(entry);
1043 @SuppressWarnings("unchecked")
1044 private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
1045 Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
1046 if (nodeTemplatesEither.isLeft()) {
1047 Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
1048 for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
1049 Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
1050 if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
1051 String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
1052 if (nodeTypesInfo.containsKey(type)) {
1053 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
1054 nodeTypeInfo.setNested(true);
1061 private boolean isGlobalSubstitute(String fileName) {
1062 return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
1065 private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
1066 if (csar.isRight()) {
1067 StorageOperationStatus value = csar.right().value();
1068 log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
1069 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1070 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
1071 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1072 return Either.right(responseFormat);
1075 Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils);
1076 if (validateCsarStatus.isRight()) {
1077 ResponseFormat responseFormat = validateCsarStatus.right().value();
1078 log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
1079 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1080 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1081 return Either.right(responseFormat);
1084 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
1086 if (toscaYamlCsarStatus.isRight()) {
1087 ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
1088 log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
1089 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1090 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1091 return Either.right(responseFormat);
1093 return toscaYamlCsarStatus;
1096 private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1097 log.trace("validating resource before create");
1098 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false);
1099 if (eitherCreator.isRight()) {
1100 return Either.right(eitherCreator.right().value());
1102 user.copyData(eitherCreator.left().value());
1104 // validate user role
1105 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
1106 if (validateRes.isRight()) {
1107 return Either.right(validateRes.right().value());
1109 // VF / PNF "derivedFrom" should be null (or ignored)
1110 if (ToscaUtils.isAtomicType(resource)) {
1111 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1112 if (validateDerivedFromNotEmpty.isRight()) {
1113 return Either.right(validateDerivedFromNotEmpty.right().value());
1116 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1119 //resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, nodeTypesArtifactsToCreate, true, false, null
1120 private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1121 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1122 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1123 boolean shouldLock, boolean inTransaction, String nodeName) {
1125 List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
1126 log.trace("************* createResourceFromYaml before parse yaml ");
1127 Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName);
1128 if (parseResourceInfoFromYamlEither.isRight()) {
1129 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
1130 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1131 return Either.right(responseFormat);
1133 log.trace("************* createResourceFromYaml after parse yaml ");
1134 ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
1135 log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
1136 log.trace("************* createResourceFromYaml before create ");
1137 Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1138 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
1139 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1140 log.trace("************* createResourceFromYaml after create ");
1141 if (createdResourceResponse.isRight()) {
1142 ResponseFormat responseFormat = createdResourceResponse.right().value();
1143 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1144 return Either.right(responseFormat);
1147 return createdResourceResponse;
1151 public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
1152 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1153 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1155 Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
1156 if (tosca_version.isRight()) {
1157 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
1158 return Either.right(responseFormat);
1160 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
1161 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
1162 Map<String, Object> mapToConvert = new HashMap<String, Object>();
1163 mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
1164 Resource vfcCreated = null;
1165 if (eitherNodeTypes.isLeft()) {
1166 Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
1167 while (nodesNameValue.hasNext()) {
1168 Entry<String, Object> nodeType = nodesNameValue.next();
1169 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1171 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1172 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1173 Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey());
1174 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1175 if (handleNeatedVfcYaml.isRight()) {
1176 return Either.right(handleNeatedVfcYaml.right().value());
1178 vfcCreated = handleNeatedVfcYaml.left().value();
1179 } else if(csarInfo.getCreatedNodesToscaResourceNames()!= null && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){
1180 log.trace("************* Going to create node {}", nodeType.getKey());
1181 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo);
1182 log.debug("************* Finished to create node {}", nodeType.getKey());
1184 if (resourceCreated.isRight()) {
1185 return Either.right(resourceCreated.right().value());
1187 vfcCreated = resourceCreated.left().value().getLeft();
1188 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName());
1190 if (vfcCreated != null) {
1191 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1193 mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
1199 private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1200 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName) {
1202 Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
1203 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1204 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1206 log.debug("************* Going to create node types from yaml {}", yamlName);
1207 Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(yamlName, resource,
1208 nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1209 if (createNodeTypesRes.isRight()) {
1210 log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, createNodeTypesRes.right().value());
1211 return Either.right(createNodeTypesRes.right().value());
1213 log.debug("************* Finished to create node types from yaml {}", yamlName);
1215 if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1216 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1217 handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1219 return handleNestedVfcRes;
1222 private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts,
1223 Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
1225 Either<Resource, ResponseFormat> result = null;
1226 Resource oldComplexVfc = null;
1227 Resource newComplexVfc = null;
1229 Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1230 if(buildCvfcRes.isRight()){
1231 log.debug("Failed to validate complex VFC for node {}. ", nodeName);
1232 result = buildCvfcRes;
1235 newComplexVfc = buildCvfcRes.left().value();
1236 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade.getLatestByToscaResourceName(newComplexVfc.getToscaResourceName());
1237 if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){
1238 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1239 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1240 } else if(oldComplexVfcRes.isLeft()){
1241 oldComplexVfc = oldComplexVfcRes.left().value();
1245 result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, newComplexVfc);
1247 if(result.isLeft()){
1248 newComplexVfc = result.left().value();
1249 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1250 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1251 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1252 result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
1253 if (result.isRight()) {
1254 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1257 if(result.isLeft()){
1258 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1259 csarInfo.getCvfcToCreateQueue().remove();
1264 private Either<Resource, ResponseFormat> handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo,
1265 CsarInfo csarInfo, String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1267 Either<Resource, ResponseFormat> handleComplexVfcRes;
1268 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1269 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1270 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
1271 markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1272 if(oldComplexVfc == null){
1273 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1274 if (handleComplexVfcRes.isRight()) {
1275 log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName);
1278 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName);
1279 if (handleComplexVfcRes.isRight()) {
1280 log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName);
1283 return handleComplexVfcRes;
1286 private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1288 Either<Resource, ResponseFormat> result = null;
1289 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1290 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1292 if(!csarInfo.getCvfcToCreateQueue().contains(nodeName)){
1293 csarInfo.getCvfcToCreateQueue().add(nodeName);
1295 log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), csarInfo.getVfResourceName());
1296 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, csarInfo.getVfResourceName(), complexVfc.getName()));
1299 result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1300 if(result.isRight()){
1301 log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
1307 private String getNodeTypeActualName(String fullName) {
1308 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1309 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1310 String resourceType = findTypes[0];
1311 return nameWithouNamespacePrefix.substring(resourceType.length());
1314 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
1315 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) {
1317 Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1318 if (resourceMetaData.isRight()) {
1319 return Either.right(resourceMetaData.right().value());
1321 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo.getVfResourceName());
1323 Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1324 if (eitherCreator.isRight()) {
1325 return Either.right(eitherCreator.right().value());
1327 user = eitherCreator.left().value();
1329 return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo);
1332 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, String csarVfName) {
1333 // We need to create a Yaml from each node_types in order to create
1334 // resource from each node type using import normative flow.
1335 DumperOptions options = new DumperOptions();
1336 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1337 Yaml yaml = new Yaml(options);
1339 Map<String, Object> node = new HashMap<>();
1340 node.put(buildNestedToscaResourceName(nodeResourceType, csarVfName, nodeNameValue.getKey()), nodeNameValue.getValue());
1341 mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1343 return yaml.dumpAsMap(mapToConvert);
1346 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1348 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1349 if (validateDerivedFromNotEmpty.isRight()) {
1350 return Either.right(validateDerivedFromNotEmpty.right().value());
1352 return Either.left(true);
1355 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1356 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) {
1358 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1359 Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
1360 return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo);
1363 private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
1364 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1366 // validate nodetype name prefix
1367 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1368 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1369 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1370 return Either.right(responseFormat);
1373 String actualName = this.getNodeTypeActualName(nodeName);
1374 String namePrefix = nodeName.replace(actualName, "");
1375 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1377 // if we import from csar, the node_type name can be
1378 // org.openecomp.resource.abstract.node_name - in this case we always
1380 if (resourceType.equals(Constants.ABSTRACT)) {
1381 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1384 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1385 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1386 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1387 return Either.right(responseFormat);
1391 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1393 // Setting type from name
1394 String type = resourceType.toUpperCase();
1395 resourceMetaData.setResourceType(type);
1397 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1398 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1399 resourceMetaData.setContactId(user.getUserId());
1400 resourceMetaData.setVendorName(resourceVf.getVendorName());
1401 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1404 List<String> tags = new ArrayList<>();
1405 tags.add(resourceMetaData.getName());
1406 resourceMetaData.setTags(tags);
1409 CategoryDefinition category = new CategoryDefinition();
1410 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1411 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1412 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1413 category.addSubCategory(subCategory);
1414 List<CategoryDefinition> categories = new ArrayList<>();
1415 categories.add(category);
1416 resourceMetaData.setCategories(categories);
1418 return Either.left(resourceMetaData);
1421 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1422 Resource cvfc = new Resource();
1423 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1424 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1425 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1426 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1427 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1428 cvfc.setAbstract(true);
1429 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1430 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1431 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1432 cvfc.setContactId(csarInfo.getModifier().getUserId());
1433 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1434 cvfc.setVendorName(resourceVf.getVendorName());
1435 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1436 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1437 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName));
1438 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1440 List<String> tags = new ArrayList<>();
1441 tags.add(cvfc.getName());
1444 CategoryDefinition category = new CategoryDefinition();
1445 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1446 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1447 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1448 category.addSubCategory(subCategory);
1449 List<CategoryDefinition> categories = new ArrayList<>();
1450 categories.add(category);
1451 cvfc.setCategories(categories);
1453 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1454 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1455 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1460 private String buildCvfcName(String resourceVfName, String nodeName) {
1461 String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1462 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1463 String resourceType = findTypes[0];
1464 return resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1) + "Cvfc";
1467 private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1468 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo,
1469 CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1470 boolean shouldLock, boolean inTransaction, String nodeName) {
1472 boolean result = true;
1473 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1476 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
1477 if (lockResult.isRight()) {
1478 ResponseFormat responseFormat = lockResult.right().value();
1479 return Either.right(responseFormat);
1481 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1484 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1485 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
1486 if (genericResourceEither.isRight()) {
1488 return genericResourceEither;
1490 Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, csarInfo.getModifier(), isNormative, inTransaction);
1491 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1492 if (createResourcesEither.isRight()) {
1494 return createResourcesEither;
1496 resource = createResourcesEither.left().value();
1497 // add groups to resource
1498 log.trace("************* Going to add inputs from yaml {}", yamlName);
1499 if (resource.shouldGenerateInputs())
1500 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
1502 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1503 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, csarInfo.getModifier(), inputs, inTransaction);
1504 if (createInputsOnResource.isRight()) {
1506 return createInputsOnResource;
1508 resource = createInputsOnResource.left().value();
1509 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1511 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
1512 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1514 createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml,
1515 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
1516 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1517 if (createResourcesEither.isRight()) {
1519 return createResourcesEither;
1522 resource = createResourcesEither.left().value();
1523 // validate update vf module group names
1524 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1525 if (validateUpdateVfGroupNamesRes.isRight()) {
1527 return Either.right(validateUpdateVfGroupNamesRes.right().value());
1529 // add groups to resource
1530 Map<String, GroupDefinition> groups;
1531 log.trace("************* Going to add groups from yaml {}", yamlName);
1533 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1534 groups = validateUpdateVfGroupNamesRes.left().value();
1536 groups = parsedToscaYamlInfo.getGroups();
1538 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, csarInfo.getModifier(), groups);
1539 if (createGroupsOnResource.isRight()) {
1541 return createGroupsOnResource;
1543 resource = createGroupsOnResource.left().value();
1544 log.trace("************* Finished to add groups from yaml {}", yamlName);
1546 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1548 if(resource.getResourceType() == ResourceTypeEnum.CVFC){
1549 if(nodeTypesArtifactsToCreate.containsKey(nodeName) && nodeTypesArtifactsToCreate.get(nodeName) !=null && !nodeTypesArtifactsToCreate.get(nodeName).isEmpty()){
1550 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
1551 handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeName), nodeTypesNewCreatedArtifacts, csarInfo.getModifier(), true, false);
1552 if(handleNodeTypeArtifactsRes.isRight()){
1553 return Either.right(handleNodeTypeArtifactsRes.right().value());
1557 Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, csarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
1559 log.trace("************* Finished to add artifacts from yaml {}", yamlName);
1560 if (createdCsarArtifactsEither.isRight()) {
1562 return createdCsarArtifactsEither;
1564 resource = createdCsarArtifactsEither.left().value();
1566 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1567 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", actionEnum, null);
1568 ASDCKpiApi.countCreatedResourcesKPI();
1569 return Either.left(resource);
1572 if (!inTransaction) {
1574 log.warn("operation failed. do rollback");
1575 titanDao.rollback();
1576 if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
1577 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1578 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
1579 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
1580 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
1581 return Either.right(componentsUtils.getResponseFormat(actionStatus, resource.getName()));
1583 log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
1587 log.debug("operation success. do commit");
1592 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
1597 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1598 if (groups != null && !groups.isEmpty()) {
1599 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1601 if (mergeGroupsUsingResource.isRight()) {
1602 log.debug("Failed to prepare groups for creation");
1603 return Either.right(mergeGroupsUsingResource.right().value());
1605 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1606 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList);
1607 if (createGroups.isRight()) {
1608 return Either.right(createGroups.right().value());
1611 return Either.left(resource);
1613 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1614 if (updatedResource.isRight()) {
1615 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1616 return Either.right(responseFormat);
1618 return Either.left(updatedResource.left().value());
1621 private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1622 if (groups != null && false == groups.isEmpty()) {
1623 List<GroupDefinition> groupsFromResource = resource.getGroups();
1624 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1626 if (mergeGroupsUsingResource.isRight()) {
1627 log.debug("Failed to prepare groups for creation");
1628 return Either.right(mergeGroupsUsingResource.right().value());
1630 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1631 List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
1632 List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
1633 List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
1634 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1635 for (GroupDefinition group : groupsAsList) {
1636 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1637 if (op.isPresent()) {
1638 GroupDefinition groupToUpdate = op.get();
1639 groupToUpdate.setMembers(group.getMembers());
1640 groupsToUpdate.add(groupToUpdate);
1642 groupsToCreate.add(group);
1645 for (GroupDefinition group : groupsFromResource) {
1646 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1647 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1649 groupsToDelete.add(group);
1654 groupsToCreate.addAll(groupsAsList);
1655 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
1656 if (!groupsToCreate.isEmpty()) {
1658 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1659 prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1661 prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1664 if (prepareGroups.isRight()) {
1665 return Either.right(prepareGroups.right().value());
1669 if (!groupsToDelete.isEmpty()) {
1670 prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
1671 if (prepareGroups.isRight()) {
1672 return Either.right(prepareGroups.right().value());
1676 if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
1677 prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
1678 if (prepareGroups.isRight()) {
1679 return Either.right(prepareGroups.right().value());
1684 return Either.left(resource);
1687 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1688 if (updatedResource.isRight()) {
1689 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1690 return Either.right(responseFormat);
1692 return Either.left(updatedResource.left().value());
1695 private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
1696 List<InputDefinition> resourceProperties = resource.getInputs();
1697 if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) {
1699 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
1700 if (createInputs.isRight()) {
1701 return Either.right(createInputs.right().value());
1704 return Either.left(resource);
1707 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1708 if (updatedResource.isRight()) {
1709 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1710 return Either.right(responseFormat);
1712 return Either.left(updatedResource.left().value());
1715 private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1717 List<GroupDefinition> result = new ArrayList<>();
1719 List<ComponentInstance> componentInstances = component.getComponentInstances();
1721 if (groups != null) {
1722 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1723 if (validateCyclicGroupsDependencies.isRight()) {
1724 return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
1726 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1727 String groupName = entry.getKey();
1729 GroupDefinition groupDefinition = entry.getValue();
1731 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1732 updatedGroupDefinition.setMembers(null);
1734 // get the members of the group
1735 Map<String, String> members = groupDefinition.getMembers();
1736 if (members != null) {
1737 Set<String> compInstancesNames = members.keySet();
1739 if (componentInstances == null || true == componentInstances.isEmpty()) {
1740 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1741 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName());
1742 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1744 // Find all component instances with the member names
1745 Map<String, String> memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1746 memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
1747 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
1749 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1751 List<String> foundMembers = new ArrayList<>();
1752 if (relevantInstances != null) {
1753 foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
1755 compInstancesNames.removeAll(foundMembers);
1756 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1757 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1758 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1761 updatedGroupDefinition.setMembers(relevantInstances);
1764 result.add(updatedGroupDefinition);
1767 return Either.left(result);
1771 * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
1776 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1778 Either<Boolean, ResponseFormat> result = Either.left(true);
1780 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1781 while (allGroupsItr.hasNext() && result.isLeft()) {
1782 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1783 // Fetches a group member A
1784 String groupAName = groupAEntry.getKey();
1785 // Finds all group members in group A
1786 Set<String> allGroupAMembersNames = new HashSet<>();
1787 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1788 // If A is a group member of itself found cyclic dependency
1789 if (allGroupAMembersNames.contains(groupAName)) {
1790 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1791 result = Either.right(responseFormat);
1794 } catch (Exception e) {
1795 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1796 result = Either.right(responseFormat);
1797 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1803 * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
1807 * @param allGroupMembers
1810 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1812 // Found Cyclic dependency
1813 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1816 GroupDefinition groupDefinition = allGroups.get(groupName);
1817 // All Members Of Current Group Resource Instances & Other Groups
1818 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1819 // Filtered Members Of Current Group containing only members which
1821 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1822 // Keep Only Elements of type group and not Resource Instances
1823 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1824 // Add Filtered Elements to main Set
1825 peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
1827 collect(Collectors.toList());
1829 // Recursively call the method for all the filtered group members
1830 for (String innerGroupName : currGroupFilteredMembers) {
1831 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1836 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1838 boolean stop = false;
1839 // In Case Not Group Stop
1840 if (!allGroups.containsKey(groupName)) {
1843 // In Case Group Has no members stop
1845 GroupDefinition groupDefinition = allGroups.get(groupName);
1846 stop = MapUtils.isEmpty(groupDefinition.getMembers());
1849 // In Case all group members already contained stop
1851 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1852 Set<String> membersOfTypeGroup = allMembers.stream().
1853 // Filter In Only Group members
1854 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1856 collect(Collectors.toSet());
1857 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1862 private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
1863 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1864 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1867 Either<Resource, ResponseFormat> result;
1868 Either<Resource, ResponseFormat> createResourcesInstancesEither;
1870 log.debug("************* Going to create all nodes {}", yamlName);
1871 Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
1872 log.debug("************* Finished to create all nodes {}", yamlName);
1873 if (createdResourcesFromdNodeTypeMap.isRight()) {
1874 log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
1875 return Either.right(createdResourcesFromdNodeTypeMap.right().value());
1878 log.debug("************* Going to create all resource instances {}", yamlName);
1879 createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes());
1881 log.debug("************* Finished to create all resource instances {}", yamlName);
1882 if (createResourcesInstancesEither.isRight()) {
1883 log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
1884 result = createResourcesInstancesEither;
1885 return createResourcesInstancesEither;
1887 resource = createResourcesInstancesEither.left().value();
1888 log.debug("************* Going to create all relations {}", yamlName);
1889 createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1891 log.debug("************* Finished to create all relations {}", yamlName);
1893 if (createResourcesInstancesEither.isRight()) {
1894 log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
1895 result = createResourcesInstancesEither;
1898 resource = createResourcesInstancesEither.left().value();
1901 log.debug("************* Going to create positions {}", yamlName);
1902 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1903 log.debug("************* Finished to set positions {}", yamlName);
1904 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
1909 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
1910 List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
1911 artifactsToAdd.stream().forEach(a -> {
1912 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1913 vfcArtifacts.add(a);
1915 log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1921 @SuppressWarnings("unchecked")
1922 private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1923 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1924 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, String nodeName) {
1926 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
1927 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1928 if (nodeTypeEntry.getValue().isNested()) {
1930 Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle,
1931 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1932 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1933 if (createResourceFromYaml.isRight()) {
1934 return Either.right(createResourceFromYaml.right().value());
1939 Map<String, Object> mappedToscaTemplate = null;
1940 if(StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)){
1941 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1943 if(MapUtils.isEmpty(mappedToscaTemplate)){
1944 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1947 Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1948 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1949 if (createdNodeTypeFromMainTemplateEither.isRight()) {
1950 ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
1951 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1952 return Either.right(responseFormat);
1955 // add the created node types to the cache although they are not in the
1957 csarInfo.getCreatedNodes().values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1962 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1963 boolean inTransaction) {
1965 if (csarInfo.getCsar() != null) {
1966 String vendorLicenseModelId = null;
1967 String vfLicenseModelId = null;
1969 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
1970 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1971 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1972 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1973 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
1974 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1975 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
1976 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1981 // Specific Behavior for license artifacts
1982 createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1983 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1984 createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1985 Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1987 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
1988 if (eitherCreateResult.isRight()) {
1989 return Either.right(eitherCreateResult.right().value());
1992 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1993 if (artifacsMetaCsarStatus.isLeft()) {
1995 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1996 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1997 Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
1998 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
1999 createArtifactsFromCsar = createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2001 createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2002 if (createArtifactsFromCsar.isRight()) {
2003 log.debug("Couldn't create artifacts from artifacts.meta");
2004 return Either.right(createArtifactsFromCsar.right().value());
2007 resource = createArtifactsFromCsar.left().value();
2009 List<GroupDefinition> groupsToDelete = resource.getGroups();
2011 if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
2012 Set<String> artifactsToDelete = new HashSet<String>();
2014 * for (GroupDefinition group : groupsToDelete) { List<String> artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either<GroupDefinition, StorageOperationStatus> deleteGroupEither =
2015 * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus =
2016 * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return
2017 * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
2019 for (String artifactId : artifactsToDelete) {
2020 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
2021 resource, null, null, shouldLock, inTransaction);
2022 if (handleDelete.isRight()) {
2023 log.debug("Couldn't delete artifact {}", artifactId);
2024 return Either.right(handleDelete.right().value());
2027 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2028 if (eitherGetResource.isRight()) {
2029 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2031 return Either.right(responseFormat);
2034 resource = eitherGetResource.left().value();
2038 return Either.left(resource);
2041 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath, String artifactFileName, String artifactType,
2042 ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
2043 boolean inTransaction) {
2044 byte[] artifactFileBytes = null;
2046 if (csarInfo.getCsar().containsKey(artifactPath)) {
2047 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
2049 Either<Boolean, ResponseFormat> result = Either.left(true);
2050 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
2051 if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
2052 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
2053 null, shouldLock, inTransaction);
2054 if (handleDelete.isRight()) {
2055 result = Either.right(handleDelete.right().value());
2060 if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
2061 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
2065 if (artifactFileBytes != null) {
2066 Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
2067 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction);
2068 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2069 if (eitherNonMetaArtifacts.isRight()) {
2070 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
2071 return Either.right(eitherNonMetaArtifacts.right().value());
2077 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2078 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
2079 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
2080 if (eitherResult.isLeft()) {
2081 createdArtifacts.add(eitherResult.left().value());
2086 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) {
2088 String jsonStr = gson.toJson(json);
2090 String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr);
2091 ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
2092 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
2093 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId,
2094 artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true, false);
2095 if (uploadArtifactToService.isRight())
2096 return Either.right(uploadArtifactToService.right().value());
2098 return Either.left(uploadArtifactToService.left().value());
2101 public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
2102 boolean shouldLock, boolean inTransaction) {
2104 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
2105 if (parseResourceInfoFromYamlEither.isRight()) {
2106 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2107 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2108 return Either.right(responseFormat);
2111 List<GroupDefinition> groups = resource.getGroups();
2112 Map<String, ArtifactDefinition> deplymentArtifact = resource.getDeploymentArtifacts();
2113 List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = new ArrayList<ArtifactDefinition>();
2114 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2115 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2116 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2119 int labelCounter = createdDeplymentArtifactsAfterDelete.size();
2121 if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
2122 if (groups != null && !groups.isEmpty()) {
2123 for (GroupDefinition group : groups) {
2124 if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) {
2125 log.debug("failed to update artifacts from csar. List of emty but group not empty");
2126 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2127 return Either.right(responseFormat);
2131 return createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
2134 // find master in group
2135 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
2137 ////////////////////////////////////// create set parsed
2138 ////////////////////////////////////// artifacts///////////////////////////////////////////
2139 Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
2140 Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
2141 Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>();
2143 for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
2144 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2145 parsedGroupTemplate.setGroupName("");
2146 Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<ArtifactTemplateInfo>();
2147 parsedArtifactsNames.add(parsedGroupTemplate);
2148 List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
2149 if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
2150 createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
2152 parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
2156 ///////////////////////////////// find artifacts to
2157 ///////////////////////////////// delete////////////////////////////////////////////////////
2159 Set<ArtifactDefinition> artifactsToDelete = new HashSet<ArtifactDefinition>();
2160 Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<String, List<ArtifactDefinition>>();
2162 Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
2163 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
2165 // Set<String> deletedArtifactsName = new HashSet<String>();
2166 Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete);
2167 if (deletedArtifactsEither.isRight()) {
2168 log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
2170 return Either.right(deletedArtifactsEither.right().value());
2173 List<ArtifactDefinition> deletedArtifacts = deletedArtifactsEither.left().value();
2175 // need to update resource if we updated artifacts
2176 if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) {
2177 for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
2178 ArtifactDefinition artToRemove = null;
2179 for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
2180 if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
2181 artToRemove = artFromResource;
2185 if (artToRemove != null)
2186 createdDeplymentArtifactsAfterDelete.remove(artToRemove);
2191 ////////////// dissociate, associate or create
2192 ////////////// artifacts////////////////////////////
2193 Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
2194 mergedgroup, deletedArtifacts);
2196 if (assDissotiateEither.isRight()) {
2197 log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
2199 return Either.right(assDissotiateEither.right().value());
2202 resource = assDissotiateEither.left().value();
2203 deplymentArtifact = resource.getDeploymentArtifacts();
2204 createdDeplymentArtifactsAfterDelete.clear();
2205 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2206 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2207 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2211 groups = resource.getGroups();
2213 // update vfModule names
2214 Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
2215 if (groups != null && !groups.isEmpty()) {
2216 Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
2217 if (validateUpdateVfGroupNamesRes.isRight()) {
2218 return Either.right(validateUpdateVfGroupNamesRes.right().value());
2220 List<GroupDefinition> heatGroups = null;
2222 heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2225 for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
2227 if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
2228 updatedGroupDef.getMembers().clear();
2230 Map<String, String> members = new HashMap<String, String>();
2231 Set<String> artifactsGroup = new HashSet<String>();
2232 artifactsGroup.addAll(updatedGroupDef.getArtifacts());
2233 associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
2234 if (!members.isEmpty()) {
2235 updatedGroupDef.setMembers(members);
2245 //////////////// create new artifacts in update
2246 //////////////// flow////////////////////////////
2247 List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<ArtifactTemplateInfo>();
2249 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2250 ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
2251 boolean isNewGroup = true;
2252 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2253 Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
2254 Set<ArtifactDefinition> group = groupArtifacts.keySet();
2255 for (ArtifactDefinition artifactInfo : group) {
2256 if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
2257 parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
2263 newArtifactsGroup.add(parsedArtifactMaster);
2266 if (!newArtifactsGroup.isEmpty()) {
2267 Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
2268 int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
2269 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter);
2270 if (validateGroupNamesRes.isRight()) {
2271 return Either.right(validateGroupNamesRes.right().value());
2273 Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
2274 if (resStatus.isRight())
2279 if (!groupForAssociateWithMembers.isEmpty()) {
2281 List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
2283 Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId);
2284 if (updateVersionEither.isRight()) {
2285 log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
2287 return Either.right(updateVersionEither.right().value());
2292 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2293 if (eitherGerResource.isRight()) {
2294 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2296 return Either.right(responseFormat);
2299 return Either.left(eitherGerResource.left().value());
2303 private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
2304 Map<String, List<ArtifactDefinition>> groupToDelete) {
2305 List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
2306 String resourceId = resource.getUniqueId();
2307 if (!artifactsToDelete.isEmpty()) {
2308 for (ArtifactDefinition artifact : artifactsToDelete) {
2309 String artifactType = artifact.getArtifactType();
2310 ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
2311 if (artifactTypeEnum == ArtifactTypeEnum.HEAT_ENV) {
2314 * Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if
2315 * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact {} . status is {}", artifact.getUniqueId(), status); ActionStatus
2316 * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); }
2318 * deletedArtifacts.add(removeArifactFromGraph.left().value());
2322 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
2323 null, null, shouldLock, inTransaction);
2324 if (handleDelete.isRight()) {
2325 return Either.right(handleDelete.right().value());
2328 deletedArtifacts.add(handleDelete.left().value().left().value());
2333 if (!groupToDelete.isEmpty()) {
2334 log.debug("try to delete group");
2335 List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
2336 List<GroupDefinition> groups = resource.getGroups();
2337 for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
2338 Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
2339 if (op.isPresent()) {
2340 groupDefinitionstoDelete.add(op.get());
2344 if (!groupDefinitionstoDelete.isEmpty()) {
2345 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete);
2346 if (prepareGroups.isRight()) {
2347 return Either.right(prepareGroups.right().value());
2351 return Either.left(deletedArtifacts);
2354 private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
2355 boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
2356 Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
2357 Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
2358 Either<Resource, ResponseFormat> resEither = Either.left(resource);
2359 for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
2360 List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts);
2361 GroupDefinition grDef = entry.getKey();
2362 if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
2363 for (ArtifactDefinition art : dissArtifactsInGroup) {
2364 grDef.getArtifacts().remove(art.getUniqueId());
2365 grDef.getArtifactsUuid().remove(art.getArtifactUUID());
2369 List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
2370 if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
2371 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
2373 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
2374 if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
2375 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
2378 if (!artifactsToUpdateMap.isEmpty()) {
2379 List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>();
2380 for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
2381 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
2382 GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
2384 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
2385 String prevUUID = artifact.getKey().getArtifactUUID();
2386 String prevId = artifact.getKey().getUniqueId();
2387 Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
2388 artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
2389 if (updateArtifactEither.isRight()) {
2390 log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
2391 resEither = Either.right(updateArtifactEither.right().value());
2394 ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
2395 if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
2396 groupToUpdate.getArtifacts().remove(prevId);
2397 groupToUpdate.getArtifactsUuid().remove(prevUUID);
2398 groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
2399 groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
2405 for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
2406 List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
2407 Set<String> arifactsUids = new HashSet<String>();
2408 Set<String> arifactsUuids = new HashSet<String>();
2409 for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
2415 boolean isCreate = true;
2416 for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
2417 if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
2418 arifactsUids.add(createdArtifact.getUniqueId());
2419 arifactsUuids.add(createdArtifact.getArtifactUUID());
2421 String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
2422 if (!heatEnvId.isEmpty()) {
2423 arifactsUids.add(heatEnvId);
2424 Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
2425 if (op.isPresent()) {
2426 this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
2435 if (isCreate) { // check if already created
2436 for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
2437 if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
2438 arifactsUids.add(createdNewArtifact.getUniqueId());
2439 arifactsUuids.add(createdNewArtifact.getArtifactUUID());
2441 String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
2442 if (!heatEnvId.isEmpty()) {
2443 arifactsUids.add(heatEnvId);
2451 Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
2452 if (createArtifactEither.isRight()) {
2453 resEither = Either.right(createArtifactEither.right().value());
2456 ArtifactDefinition createdArtifact = createArtifactEither.left().value();
2457 arifactsUids.add(createdArtifact.getUniqueId());
2458 arifactsUuids.add(createdArtifact.getArtifactUUID());
2459 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
2460 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2461 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2462 resource.getName(), csarInfo.getModifier(), resource, null);
2463 if (createHeatEnvPlaceHolder.isRight()) {
2464 return Either.right(createHeatEnvPlaceHolder.right().value());
2466 String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
2467 arifactsUids.add(heatEnvId);
2472 if (arifactsUids.size() > 0) {
2473 List<String> artifactsToAssociate = new ArrayList<String>();
2474 artifactsToAssociate.addAll(arifactsUids);
2475 GroupDefinition assotiateGroup = associateEntry.getKey();
2476 assotiateGroup.getArtifacts().addAll(arifactsUids);
2477 assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
2482 * if (!associateArtifactGroup.isEmpty()) {
2484 * log.debug("Try to associate artifacts to groups.");
2486 * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
2487 * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
2492 ComponentParametersView parametersView = new ComponentParametersView();
2493 parametersView.disableAll();
2494 parametersView.setIgnoreComponentInstances(false);
2495 parametersView.setIgnoreUsers(false);
2496 parametersView.setIgnoreArtifacts(false);
2497 parametersView.setIgnoreGroups(false);
2499 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2501 if (eitherGerResource.isRight()) {
2502 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2504 resEither = Either.right(responseFormat);
2508 resEither = Either.left(eitherGerResource.left().value());
2512 private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
2513 Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
2514 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
2515 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2516 Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
2517 boolean isNeedToDeleteGroup = true;
2518 List<ArtifactDefinition> listToDelete = null;
2519 for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
2520 listToDelete = createdArtifactMap.get(maserArtifact);
2521 for (ArtifactDefinition artToDelete : listToDelete) {
2522 findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
2524 if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
2525 GroupDefinition group = groupListEntry.getKey();
2526 for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
2527 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
2528 group.getArtifacts().remove(artifactDefinition.getUniqueId());
2531 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
2532 group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
2539 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
2540 if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
2541 MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
2542 mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
2543 mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
2544 mergedgroup.put(groupListEntry.getKey(), mergedGroup);
2545 isNeedToDeleteGroup = false;
2551 if (isNeedToDeleteGroup) {
2552 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
2559 private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
2560 List<ArtifactDefinition> createdDeplymentArtifacts) {
2561 boolean isNeedToDeleteArtifact = true;
2562 String artifactType = artifact.getArtifactType();
2563 ArtifactDefinition generatedFromArt = null;
2564 if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
2565 Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
2567 generatedFromArt = op.get();
2571 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2572 Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
2573 for (ArtifactTemplateInfo template : artifactsNames) {
2574 if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
2575 isNeedToDeleteArtifact = false;
2579 if (generatedFromArt != null) {
2580 if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
2581 isNeedToDeleteArtifact = false;
2589 if (isNeedToDeleteArtifact) {
2590 artifactsToDelete.add(artifact);
2595 private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
2596 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>();
2598 for (GroupDefinition group : groups) {
2599 Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>();
2600 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
2601 List<String> artifactsList = group.getArtifacts();
2602 if (artifactsList != null && !artifactsList.isEmpty()) {
2604 ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList);
2605 if (masterArtifact != null)
2606 gupsMap.put(masterArtifact, artifacts);
2607 groupArtifact.put(group, gupsMap);
2611 return groupArtifact;
2614 private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
2616 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2617 parsedArtifactsName.add(parsedGroupTemplate);
2618 List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
2619 if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
2620 createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
2625 public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
2626 boolean shouldLock, boolean inTransaction) {
2628 log.debug("parseResourceArtifactsInfoFromFile start");
2629 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
2630 if (parseResourceInfoFromYamlEither.isRight()) {
2631 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2632 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2633 return Either.right(responseFormat);
2635 log.debug("parseResourceArtifactsInfoFromFile end");
2637 log.debug("createResourceArtifacts start");
2638 Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
2639 if (respStatus.isRight()) {
2642 log.debug("createResourceArtifacts end");
2643 log.debug("getResource start");
2644 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2645 log.debug("getResource end");
2646 if (eitherGerResource.isRight()) {
2647 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2649 return Either.right(responseFormat);
2652 return Either.left(eitherGerResource.left().value());
2656 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
2657 List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
2658 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2659 List<GroupDefinition> createdGroups = resource.getGroups();
2660 List<GroupDefinition> heatGroups = null;
2661 if (createdGroups != null && !createdGroups.isEmpty()) {
2662 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2665 List<GroupDefinition> needToAdd = new ArrayList<>();
2666 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2667 String groupName = groupTemplateInfo.getGroupName();
2668 Set<String> artifactsGroup = new HashSet<String>();
2669 Set<String> artifactsUUIDGroup = new HashSet<String>();
2671 resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
2672 if (resStatus.isRight())
2675 Map<String, String> members = new HashMap<String, String>();
2676 associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
2678 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2679 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2681 GroupDefinition groupDefinition = new GroupDefinition();
2682 groupDefinition.setName(groupName);
2683 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2684 groupDefinition.setArtifacts(artifactsList);
2685 groupDefinition.setArtifactsUuid(artifactsUUIDList);
2687 if (!members.isEmpty())
2688 groupDefinition.setMembers(members);
2690 List<GroupProperty> properties = new ArrayList<GroupProperty>();
2691 GroupProperty prop = new GroupProperty();
2692 prop.setName(Constants.IS_BASE);
2693 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2694 properties.add(prop);
2696 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2697 createdArtifacts.addAll(createdNewArtifacts);
2698 createdArtifacts.addAll(artifactsFromResource);
2699 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2700 if (getLatestGroupTypeRes.isRight()) {
2701 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2703 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2704 groupDefinition.convertFromGroupProperties(properties);
2706 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2707 // if (createGroup.isRight())
2708 // return Either.right(createGroup.right().value());
2709 needToAdd.add(groupDefinition);
2711 ComponentParametersView componentParametersView = new ComponentParametersView();
2712 componentParametersView.disableAll();
2713 componentParametersView.setIgnoreArtifacts(false);
2714 componentParametersView.setIgnoreGroups(false);
2715 componentParametersView.setIgnoreComponentInstances(false);
2717 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2718 if (component.isRight()) {
2719 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2721 resource = component.left().value();
2723 Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd);
2724 if (addGroups.isRight())
2725 return Either.right(addGroups.right().value());
2730 private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
2731 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
2732 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2733 String artifactFileName = artifactTemplateInfo.getFileName();
2734 String artifactUid = "";
2735 String artifactUUID = "";
2736 String artifactEnvUid = "";
2737 boolean alreadyExist = false;
2739 // check if artifacts already exist
2740 if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
2741 for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
2742 if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
2743 artifactUid = artifactFromResource.getUniqueId();
2744 artifactUUID = artifactFromResource.getArtifactUUID();
2745 if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2746 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
2747 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2748 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
2750 alreadyExist = true;
2751 artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
2758 if (!alreadyExist) {
2759 for (ArtifactDefinition createdArtifact : createdArtifacts) {
2760 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
2761 artifactUid = createdArtifact.getUniqueId();
2762 artifactUUID = createdArtifact.getArtifactUUID();
2764 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2765 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
2766 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2767 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
2769 alreadyExist = true;
2770 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
2776 // if not exist need to create
2777 if (!alreadyExist) {
2779 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
2780 if (newArtifactEither.isRight()) {
2781 resStatus = Either.right(newArtifactEither.right().value());
2784 ArtifactDefinition newArtifact = newArtifactEither.left().value();
2785 artifactUid = newArtifact.getUniqueId();
2786 artifactUUID = newArtifact.getArtifactUUID();
2787 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
2788 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2789 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2790 resource.getName(), csarInfo.getModifier(), resource, null);
2791 if (createHeatEnvPlaceHolder.isRight()) {
2792 return Either.right(createHeatEnvPlaceHolder.right().value());
2794 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
2798 artifactsGroup.add(artifactUid);
2799 artifactsUUIDGroup.add(artifactUUID);
2800 if (!artifactEnvUid.isEmpty()) {
2801 artifactsGroup.add(artifactEnvUid);
2804 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
2805 if (relatedArtifacts != null) {
2806 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
2807 resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
2808 if (resStatus.isRight())
2815 private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
2816 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
2818 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2820 Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
2822 for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
2823 if (groupTemplateList != null) {
2824 resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
2825 if (resStatus.isRight())
2834 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) {
2836 Either<Resource, ResponseFormat> resStatus = null;
2837 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2840 List<NonMetaArtifactInfo> artifactPathAndNameList =
2841 // Stream of file paths contained in csar
2842 csarInfo.getCsar().entrySet().stream()
2843 // Filter in only VF artifact path location
2844 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
2845 // Validate and add warnings
2846 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2847 // Filter in Non Warnings
2848 .filter(e -> e.isLeft())
2849 // Convert from Either to NonMetaArtifactInfo
2850 .map(e -> e.left().value())
2852 .collect(Collectors.toList());
2854 Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
2855 if (responseFormatEither.isRight()) {
2856 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
2860 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2862 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
2863 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2864 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
2866 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, csarInfo.getModifier());
2868 if (findVfCsarArtifactsToHandleRes.isRight()) {
2869 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2871 if (resStatus == null) {
2872 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2875 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2876 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
2878 Optional<ResponseFormat> optionalCreateInDBError =
2879 // Stream of artifacts to be created
2880 currArtifactOperationPair.getValue().stream()
2881 // create each artifact
2882 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2883 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
2885 // filter in only error
2886 .filter(e -> e.isRight()).
2887 // Convert the error from either to ResponseFormat
2888 map(e -> e.right().value()).
2889 // Check if an error occurred
2891 // Error found on artifact Creation
2892 if (optionalCreateInDBError.isPresent()) {
2893 resStatus = Either.right(optionalCreateInDBError.get());
2898 if (resStatus == null) {
2899 resStatus = Either.left(resource);
2901 } catch (Exception e) {
2902 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2903 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2905 CsarUtils.handleWarningMessages(collectedWarningMessages);
2910 private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
2911 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2912 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2913 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2914 return Either.right(nonMetaArtifactInfo.getArtifactName());
2917 return Either.left(true);
2921 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2923 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2924 // collect all Deployment and Informational artifacts of VF
2925 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2926 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2928 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2929 existingArtifacts.addAll(resource.getArtifacts().values());
2931 existingArtifacts = existingArtifacts.stream()
2932 // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
2933 .filter(this::isNonMetaArtifact).collect(Collectors.toList());
2935 List<String> artifactsToIgnore = new ArrayList<>();
2936 // collect IDs of Artifacts of VF which belongs to any group
2937 if (resource.getGroups() != null) {
2938 resource.getGroups().stream().forEach(g -> {
2939 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
2940 artifactsToIgnore.addAll(g.getArtifacts());
2943 existingArtifacts = existingArtifacts.stream()
2944 // filter artifacts which belongs to any group
2945 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
2946 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2949 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2950 boolean result = true;
2951 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2957 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2958 boolean result = true;
2959 if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2965 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
2966 int labelCounter, boolean shouldLock, boolean inTransaction) {
2967 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2968 List<GroupDefinition> createdGroups = resource.getGroups();
2969 List<GroupDefinition> heatGroups = null;
2970 if (createdGroups != null && !createdGroups.isEmpty()) {
2972 // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
2973 // e.getArtifacts().stream()).filter(p ->
2974 // relevantArtifactTypes.contains(p.getArtifactType()
2975 // )).collect(Collectors.toList());
2976 // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
2977 // e -> e.getProperties().stream().filter(p ->
2978 // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
2979 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2982 List<GroupDefinition> needToCreate = new ArrayList<>();
2983 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2984 String groupName = groupTemplateInfo.getGroupName();
2985 Set<String> artifactsGroup = new HashSet<String>();
2986 Set<String> artifactsUUIDGroup = new HashSet<String>();
2988 log.debug("createDeploymentArtifactsFromCsar start");
2989 resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
2990 log.debug("createDeploymentArtifactsFromCsar end");
2991 if (resStatus.isRight())
2994 Map<String, String> members = new HashMap<String, String>();
2995 associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
2997 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2998 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
3000 GroupDefinition groupDefinition = new GroupDefinition();
3001 groupDefinition.setName(groupName);
3002 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
3003 groupDefinition.setArtifacts(artifactsList);
3004 groupDefinition.setArtifactsUuid(artifactsUUIDList);
3006 if (!members.isEmpty())
3007 groupDefinition.setMembers(members);
3008 List<GroupProperty> properties = new ArrayList<GroupProperty>();
3009 GroupProperty prop = new GroupProperty();
3010 prop.setName(Constants.IS_BASE);
3011 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
3012 properties.add(prop);
3013 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
3014 if (getLatestGroupTypeRes.isRight()) {
3015 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
3017 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
3018 groupDefinition.convertFromGroupProperties(properties);
3019 log.debug("createGroup start");
3021 // Since in these groups we handle only artifacts, then no need to
3022 // fetch component instances
3024 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
3025 // log.debug("createGroup end");
3026 // if (createGroup.isRight())
3027 // return Either.right(createGroup.right().value());
3028 needToCreate.add(groupDefinition);
3031 ComponentParametersView componentParametersView = new ComponentParametersView();
3032 componentParametersView.disableAll();
3033 componentParametersView.setIgnoreUsers(false);
3034 componentParametersView.setIgnoreArtifacts(false);
3035 componentParametersView.setIgnoreGroups(false);
3037 componentParametersView.setIgnoreComponentInstances(false);
3039 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
3040 if (component.isRight()) {
3041 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3044 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate);
3045 if (createGroups.isRight()) {
3046 return Either.right(createGroups.right().value());
3052 public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
3053 Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
3054 vfModuleProperties.entrySet().forEach(p -> {
3055 GroupProperty prop = new GroupProperty();
3056 prop.setName(p.getKey());
3058 prop.setValue(p.getValue().getForBaseModule());
3059 prop.setDefaultValue(p.getValue().getForBaseModule());
3061 prop.setValue(p.getValue().getForNonBaseModule());
3062 prop.setDefaultValue(p.getValue().getForNonBaseModule());
3064 properties.add(prop);
3067 GroupProperty proplabel = new GroupProperty();
3068 proplabel.setName("vf_module_label");
3070 Matcher matcher = pattern.matcher(moduleName);
3072 if (matcher.find()) {
3073 proplabel.setValue(matcher.group(1));
3074 proplabel.setDefaultValue(matcher.group(1));
3076 proplabel.setValue(moduleName);
3077 proplabel.setDefaultValue(moduleName);
3079 properties.add(proplabel);
3081 GroupProperty propvolume = new GroupProperty();
3082 propvolume.setName("volume_group");
3083 boolean isVolume = false;
3084 for (String artifactId : artifactsInGroup) {
3085 ArtifactDefinition artifactDef = null;
3086 artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
3087 if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
3092 propvolume.setValue(String.valueOf(isVolume));
3093 propvolume.setDefaultValue(String.valueOf(isVolume));
3094 properties.add(propvolume);
3095 mergeWithGroupTypeProperties(properties, groupType.getProperties());
3099 private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
3101 Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
3102 for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
3103 if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
3104 properties.add(new GroupProperty(groupTypeProperty));
3109 private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
3110 for (ArtifactDefinition artifact : createdArtifacts) {
3111 if (artifact.getUniqueId().equals(artifactId)) {
3118 private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
3119 if (heatGroups != null && !heatGroups.isEmpty()) {
3120 for (GroupDefinition heatGroup : heatGroups) {
3121 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
3122 if (grpoupProps != null) {
3123 Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
3124 if (op.isPresent()) {
3125 GroupProperty prop = op.get();
3126 String heatFileNAme = prop.getValue();
3127 if (null == heatFileNAme || heatFileNAme.isEmpty())
3129 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
3130 for (String artifactId : artifactsGroup) {
3131 Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3132 if (opArt.isPresent()) {
3133 artifacts.add(opArt.get());
3135 if (artifactsFromResource != null) {
3136 opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3137 if (opArt.isPresent()) {
3138 artifacts.add(opArt.get());
3142 Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
3143 if (resOp.isPresent()) {
3144 members.putAll(heatGroup.getMembers());
3153 private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
3154 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3155 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
3156 String artifactFileName = artifactTemplateInfo.getFileName();
3157 String artifactUid = "";
3158 String artifactEnvUid = "";
3159 String artifactUUID = "";
3160 boolean alreadyExist = false;
3162 // check if artifacts already exist
3163 for (ArtifactDefinition createdArtifact : createdArtifacts) {
3164 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
3165 artifactUid = createdArtifact.getUniqueId();
3166 artifactUUID = createdArtifact.getArtifactUUID();
3167 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3168 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
3169 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3170 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
3172 alreadyExist = true;
3173 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
3177 // if not exist need to create
3178 if (!alreadyExist) {
3180 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3181 if (newArtifactEither.isRight()) {
3182 resStatus = Either.right(newArtifactEither.right().value());
3185 ArtifactDefinition newArtifact = newArtifactEither.left().value();
3186 artifactUid = newArtifact.getUniqueId();
3187 artifactUUID = newArtifact.getArtifactUUID();
3189 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
3190 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3191 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
3192 resource.getName(), csarInfo.getModifier(), resource, null);
3193 if (createHeatEnvPlaceHolder.isRight()) {
3194 return Either.right(createHeatEnvPlaceHolder.right().value());
3196 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
3200 artifactsGroup.add(artifactUid);
3201 artifactsUUIDGroup.add(artifactUUID);
3202 if (!artifactEnvUid.isEmpty()) {
3203 artifactsGroup.add(artifactEnvUid);
3206 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3207 if (relatedArtifacts != null) {
3208 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
3209 resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3210 if (resStatus.isRight())
3217 private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
3218 String artifactEnvUid = "";
3219 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
3220 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3221 artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
3223 return artifactEnvUid;
3226 private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
3227 List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3228 final String artifactFileName = artifactTemplateInfo.getFileName();
3229 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils);
3230 if (artifactContententStatus.isRight()) {
3231 return Either.right(artifactContententStatus.right().value());
3233 labelCounter += createdArtifacts.size();
3235 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3237 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3238 shoudLock, inTransaction);
3240 if (uploadArtifactToService.isRight())
3241 return Either.right(uploadArtifactToService.right().value());
3243 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3244 if (currentInfo.getHeatParameters() != null) {
3246 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, false);
3247 if (updateEnvEither.isRight()) {
3248 log.debug("failed to update parameters to artifact {}", artifactFileName);
3249 return Either.right(updateEnvEither.right().value());
3252 currentInfo = updateEnvEither.left().value();
3256 createdArtifacts.add(currentInfo);
3258 return Either.left(currentInfo);
3262 private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
3263 List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
3265 Either<ArtifactDefinition, ResponseFormat> resStatus = null;
3266 String artifactFileName = artifactTemplateInfo.getFileName();
3268 // check if artifacts already exist
3269 for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
3270 if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
3271 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3272 log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
3273 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3274 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
3277 resStatus = Either.left(updatedArtifact);
3283 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
3284 if (artifactContententStatus.isRight()) {
3285 resStatus = Either.right(artifactContententStatus.right().value());
3289 Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
3290 oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
3292 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
3293 shouldLock, inTransaction);
3295 if (uploadArtifactToService.isRight()) {
3296 resStatus = Either.right(uploadArtifactToService.right().value());
3299 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3301 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, true);
3302 if (updateEnvEither.isRight()) {
3303 log.debug("failed to update parameters to artifact {}", artifactFileName);
3304 resStatus = Either.right(updateEnvEither.right().value());
3307 // TODO evg update env time ( must be separate US for this!!!!)
3309 updatedArtifacts.add(updateEnvEither.left().value());
3310 resStatus = Either.left(updateEnvEither.left().value());
3316 private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
3317 Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
3318 if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
3320 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
3322 if (artifactparamsStatus.isRight()) {
3323 resStatus = Either.right(artifactparamsStatus.right().value());
3326 Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
3328 * if (propsStatus.isRight()) {
3330 * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
3332 if (propsStatus.isLeft()) {
3333 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
3334 List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
3335 // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3337 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3340 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3342 paramName = heatEnvParam.getName();
3343 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3344 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3346 String updatedParamValue = heatEnvParam.getCurrentValue();
3347 if (updatedParamValue == null)
3348 updatedParamValue = heatEnvParam.getDefaultValue();
3349 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3350 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3351 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3352 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3353 resStatus = Either.right(responseFormat);
3356 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3357 // newHeatEnvParams.add(currHeatParam);
3362 currentInfo.setListHeatParameters(currentHeatEnvParams);
3363 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
3364 if (updateArifactOnResource.isRight()) {
3365 log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
3366 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3368 resStatus = Either.left(updateArifactOnResource.left().value());
3373 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3374 Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
3375 if (op.isPresent()) {
3376 ArtifactDefinition artifactInfoHeatEnv = op.get();
3377 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
3378 if (updateArifactOnResource.isRight()) {
3379 log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
3380 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3387 private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
3388 // extract heat parameters
3389 String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
3390 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
3391 if (heatParameters.isRight()) {
3392 log.debug("File {} is not in expected key-value form in csar ", fileName);
3393 BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR);
3394 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
3397 return Either.left(heatParameters.left().value());
3401 private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) {
3403 Map<String, Object> json = new HashMap<String, Object>();
3404 String artifactName = artifactTemplateInfo.getFileName();
3406 json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
3407 json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
3408 json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
3410 // DE250204: There is no need to check if base64 encoding.
3412 // String encodedPayload = new String(artifactContentent);
3413 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3414 // if (!isEncoded) {
3415 String encodedPayload = Base64.encodeBase64String(artifactContentent);
3417 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3418 String displayName = artifactName;
3419 if (artifactName.lastIndexOf(".") > 0)
3420 displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
3421 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3422 String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
3423 json.put(Constants.ARTIFACT_LABEL, label);
3424 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
3425 List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3426 json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
3427 : 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()));
3431 private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
3432 List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3434 Map<String, Object> json = new HashMap<String, Object>();
3435 if (artifactId != null && !artifactId.isEmpty())
3436 json.put(Constants.ARTIFACT_ID, artifactId);
3438 json.put(Constants.ARTIFACT_NAME, artifactName);
3439 json.put(Constants.ARTIFACT_TYPE, artifactType);
3440 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3442 String encodedPayload = new String(artifactContentent);
3444 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3445 // if (!isEncoded) {
3446 log.debug("payload is encoded. perform decode");
3447 encodedPayload = Base64.encodeBase64String(artifactContentent);
3450 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3451 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3452 json.put(Constants.ARTIFACT_LABEL, label);
3453 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3454 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3455 : 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()));
3459 @SuppressWarnings({ "unchecked", "static-access" })
3460 private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
3463 JsonObject jsonElement = new JsonObject();
3464 jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
3466 JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
3467 if (importStructureElement == null || importStructureElement.isJsonNull()) {
3468 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3469 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3470 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3473 Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>();
3474 artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
3475 if (artifactTemplateMap.isEmpty()) {
3476 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3477 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3478 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3481 Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
3482 Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>();
3483 List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
3484 for (String artifactsTypeKey : artifactsTypeKeys) {
3486 List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
3487 Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
3488 if (artifactTemplateInfoListPairStatus.isRight()) {
3489 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3490 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3491 return Either.right(artifactTemplateInfoListPairStatus.right().value());
3493 List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
3494 if (artifactTemplateInfoList == null) {
3495 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3496 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3497 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3500 allGroups.addAll(artifactTemplateInfoList);
3501 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList);
3503 int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
3504 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
3505 if (validateGroupNamesRes.isRight()) {
3506 return Either.right(validateGroupNamesRes.right().value());
3508 return Either.left(artifactsMap);
3509 } catch (Exception e) {
3510 log.debug("Artifact file is not in expected format, fileName {}", artifactFileName);
3511 log.debug("failed with exception.", e);
3512 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3513 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3518 private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) {
3519 List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>();
3520 for (Map<String, Object> o : jsonObject) {
3521 Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
3522 if (artifacttemplateInfoStatus.isRight()) {
3523 return Either.right(artifacttemplateInfoStatus.right().value());
3526 ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
3527 if (artifacttemplateInfo != null) {
3528 artifactTemplateInfoList.add(artifacttemplateInfo);
3532 return Either.left(artifactTemplateInfoList);
3535 private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3536 log.debug("createResourceInstancesRelations try to create relations ");
3537 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3538 if (uploadResInstancesMap == null) {
3539 log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
3540 BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR);
3542 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3543 return Either.right(responseFormat);
3546 if (componentInstancesList == null || componentInstancesList.isEmpty()) {
3547 log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
3548 BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3550 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3551 return Either.right(responseFormat);
3554 log.debug("Before validateAndUpdatePropertyValue");
3555 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
3556 if (allDataTypes.isRight()) {
3557 TitanOperationStatus status = allDataTypes.right().value();
3558 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
3559 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
3563 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
3564 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
3565 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
3566 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
3567 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
3568 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
3569 Map<String, Resource> originCompMap = new HashMap<>();
3570 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
3572 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
3574 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3575 log.trace("Processing entry: {}", entry);
3576 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3577 ComponentInstance currentCompInstance = null;
3578 for (ComponentInstance compInstance : componentInstancesList) {
3579 log.trace("Processing component instance: {}", compInstance);
3580 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3581 currentCompInstance = compInstance;
3586 if (currentCompInstance == null) {
3587 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3588 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3589 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3590 return Either.right(responseFormat);
3592 String resourceInstanceId = currentCompInstance.getUniqueId();
3593 Resource originResource;
3594 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
3595 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
3596 if (getOriginResourceRes.isRight()) {
3597 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), getOriginResourceRes);
3598 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
3599 return Either.right(responseFormat);
3601 originResource = getOriginResourceRes.left().value();
3602 originCompMap.put(originResource.getUniqueId(), originResource);
3604 originResource = originCompMap.get(currentCompInstance.getComponentUid());
3606 if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
3607 instCapabilties.put(currentCompInstance, originResource.getCapabilities());
3608 if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
3609 instRequirements.put(currentCompInstance, originResource.getRequirements());
3610 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
3611 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
3612 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
3613 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
3614 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
3615 instAttributes.put(resourceInstanceId, originResource.getAttributes());
3616 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
3617 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
3618 if (addPropertiesValueToRiRes.getStatus() != 200) {
3619 return Either.right(addPropertiesValueToRiRes);
3622 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(originResource);
3623 if (genericResourceEither.isRight()) {
3624 return genericResourceEither;
3626 log.trace("************* Going to add inputs from from original resource {} to resource instance. ", originResource.getName());
3627 if (originResource.shouldGenerateInputs())
3628 generateInputsFromGenericTypeProperties(originResource, genericResourceEither.left().value());
3630 ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
3631 if (addInputValueToRiRes.getStatus() != 200) {
3632 return Either.right(addInputValueToRiRes);
3637 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
3638 if (addPropToInst.isRight()) {
3639 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
3640 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
3641 return Either.right(responseFormat);
3643 if (instInputs != null && !instInputs.isEmpty()) {
3644 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
3645 if (addInputToInst.isRight()) {
3646 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
3647 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
3648 return Either.right(responseFormat);
3651 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
3652 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3653 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3654 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3655 return Either.right(responseFormat);
3658 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user);
3659 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3660 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3661 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3662 return Either.right(responseFormat);
3665 addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
3666 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3667 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3668 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3669 return Either.right(responseFormat);
3672 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
3673 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3674 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3675 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3676 return Either.right(responseFormat);
3679 ComponentParametersView parametersView = new ComponentParametersView();
3680 parametersView.disableAll();
3681 parametersView.setIgnoreComponentInstances(false);
3682 parametersView.setIgnoreComponentInstancesProperties(false);
3683 parametersView.setIgnoreCapabilities(false);
3684 parametersView.setIgnoreRequirements(false);
3686 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
3688 if (eitherGetResource.isRight()) {
3689 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3691 return Either.right(responseFormat);
3695 resource = eitherGetResource.left().value();
3697 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3698 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3699 ComponentInstance currentCompInstance = null;
3700 for (ComponentInstance compInstance : componentInstancesList) {
3702 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3703 currentCompInstance = compInstance;
3708 if (currentCompInstance == null) {
3709 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3710 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3711 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3712 return Either.right(responseFormat);
3715 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
3716 if (addRelationToRiRes.getStatus() != 200) {
3717 return Either.right(addRelationToRiRes);
3721 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
3722 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3723 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3724 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3725 return Either.right(responseFormat);
3728 log.debug("************* in create relations, getResource start");
3730 eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3731 log.debug("************* in create relations, getResource end");
3732 if (eitherGetResource.isRight()) {
3733 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3735 return Either.right(responseFormat);
3738 resource = eitherGetResource.left().value();
3739 if(resource.getResourceType() == ResourceTypeEnum.CVFC){
3740 eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
3741 if (eitherGetResource.isRight()) {
3742 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3743 return Either.right(responseFormat);
3746 return Either.left(eitherGetResource.left().value());
3749 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3750 Either<Resource, StorageOperationStatus> updateRes = null;
3751 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3752 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3753 StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements( resource.getUniqueId());
3754 if(status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND){
3755 log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", resource.getUniqueId(), status);
3756 updateRes = Either.right(status);
3758 if(updateRes == null){
3759 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities, updatedInstRequirements);
3760 status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource.getUniqueId());
3761 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3762 log.debug("Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", resource.getUniqueId(), status);
3763 updateRes = Either.right(status);
3766 if(updateRes == null){
3767 updateRes = toscaOperationFacade.getToscaElement( resource.getUniqueId());
3773 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3774 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3776 componentInstances.stream().forEach( i -> {
3777 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
3778 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
3782 private void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3783 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3784 Set<String> updatedReqNames = new HashSet<>();
3785 if(MapUtils.isNotEmpty(requirementsNamesToUpdate)){
3786 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
3787 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream()
3788 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3789 .map(r ->{r.setParentName(r.getName()); r.setName(requirementsNamesToUpdate.get(r.getName())); updatedReqNames.add(r.getName()); return r;})
3790 .collect(Collectors.toList()));
3793 if(MapUtils.isNotEmpty(updatedRequirements)){
3794 updatedInstRequirements.put(instance, updatedRequirements);
3798 private void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3799 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3800 Set<String> updatedCapNames = new HashSet<>();
3801 if(MapUtils.isNotEmpty(capabilitiesNamesToUpdate)){
3802 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
3803 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream()
3804 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3805 .map(c -> {c.setParentName(c.getName()); c.setName(capabilitiesNamesToUpdate.get(c.getName())); updatedCapNames.add(c.getName()); return c;})
3806 .collect(Collectors.toList()));
3809 if(MapUtils.isNotEmpty(updatedCapabilities)){
3810 updatedInstCapabilties.put(instance, updatedCapabilities);
3814 private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3815 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3817 UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
3819 ComponentInstance currentCompInstance = null;
3821 for (ComponentInstance compInstance : componentInstancesList) {
3823 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3824 currentCompInstance = compInstance;
3830 if (currentCompInstance == null) {
3831 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3832 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3833 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3834 return responseFormat;
3836 String resourceInstanceId = currentCompInstance.getUniqueId();
3838 Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
3840 if (regMap != null) {
3841 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
3843 while (nodesRegValue.hasNext()) {
3844 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3846 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3847 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3848 log.debug("Going to create relation {}", uploadRegInfo.getName());
3849 String regName = uploadRegInfo.getName();
3850 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3851 regCapRelDef.setFromNode(resourceInstanceId);
3852 log.debug("try to find available requirement {} ", regName);
3853 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
3854 if (eitherReqStatus.isRight()) {
3855 log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
3856 return eitherReqStatus.right().value();
3859 RequirementDefinition validReq = eitherReqStatus.left().value();
3860 List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
3861 if (reqAndRelationshipPairList == null)
3862 reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
3863 RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
3864 reqAndRelationshipPair.setRequirement(regName);
3865 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3866 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3867 RelationshipImpl relationship = new RelationshipImpl();
3868 relationship.setType(validReq.getCapability());
3869 reqAndRelationshipPair.setRelationships(relationship);
3871 ComponentInstance currentCapCompInstance = null;
3872 for (ComponentInstance compInstance : componentInstancesList) {
3873 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
3874 currentCapCompInstance = compInstance;
3879 if (currentCapCompInstance == null) {
3880 log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
3881 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3882 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3883 return responseFormat;
3885 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3886 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3887 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
3888 if (aviableCapForRel == null) {
3889 log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
3890 BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
3891 ErrorSeverity.ERROR);
3892 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3893 return responseFormat;
3895 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3896 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3897 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3898 reqAndRelationshipPairList.add(reqAndRelationshipPair);
3899 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3900 relations.add(regCapRelDef);
3903 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3904 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3905 return responseFormat;
3907 return componentsUtils.getResponseFormat(ActionStatus.OK);
3910 private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3911 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3912 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3913 if (propMap != null && propMap.size() > 0) {
3914 Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
3916 List<InputDefinition> listFromMap = originResource.getInputs();
3917 if (listFromMap == null || listFromMap.isEmpty()) {
3918 log.debug("failed to find properties ");
3919 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3920 return responseFormat;
3922 for (InputDefinition prop : listFromMap) {
3923 String propName = prop.getName();
3924 if (!currPropertiesMap.containsKey(propName)) {
3925 currPropertiesMap.put(propName, prop);
3928 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3929 for (List<UploadPropInfo> propertyList : propMap.values()) {
3931 UploadPropInfo propertyInfo = propertyList.get(0);
3932 String propName = propertyInfo.getName();
3933 if (!currPropertiesMap.containsKey(propName)) {
3934 log.debug("failed to find property {} ", propName);
3935 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3936 return responseFormat;
3938 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3939 ComponentInstanceInput property = null;
3941 String value = null;
3942 List<GetInputValueDataDefinition> getInputs = null;
3943 boolean isValidate = true;
3944 if (propertyInfo.getValue() != null) {
3945 getInputs = propertyInfo.getGet_input();
3946 isValidate = getInputs == null || getInputs.isEmpty();
3948 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3950 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
3952 String innerType = null;
3953 property = new ComponentInstanceInput(curPropertyDef, value, null);
3955 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
3956 if (validatevalueEiter.isRight()) {
3957 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3960 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
3961 // property.setUniqueId(uniqueId);
3962 property.setValue(validatevalueEiter.left().value());
3964 if (getInputs != null && !getInputs.isEmpty()) {
3965 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3966 for (GetInputValueDataDefinition getInput : getInputs) {
3967 List<InputDefinition> inputs = resource.getInputs();
3968 if (inputs == null || inputs.isEmpty()) {
3969 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
3970 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3973 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3974 if (!optional.isPresent()) {
3975 log.debug("Failed to find input {} ", getInput.getInputName());
3976 // @@TODO error message
3977 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3979 InputDefinition input = optional.get();
3980 getInput.setInputId(input.getUniqueId());
3981 getInputValues.add(getInput);
3983 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3984 if (getInputIndex != null) {
3985 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
3986 if (!optional.isPresent()) {
3987 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3988 // @@TODO error message
3989 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3991 InputDefinition inputIndex = optional.get();
3992 getInputIndex.setInputId(inputIndex.getUniqueId());
3993 getInputValues.add(getInputIndex);
3996 property.setGetInputValues(getInputValues);
3998 instPropList.add(property);
3999 // delete overriden property
4000 currPropertiesMap.remove(property.getName());
4002 // add rest of properties
4003 if (!currPropertiesMap.isEmpty()) {
4004 for (InputDefinition value : currPropertiesMap.values()) {
4005 instPropList.add(new ComponentInstanceInput(value));
4008 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
4010 return componentsUtils.getResponseFormat(ActionStatus.OK);
4013 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
4014 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
4016 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
4017 if (propMap != null && propMap.size() > 0) {
4018 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
4020 List<PropertyDefinition> listFromMap = originResource.getProperties();
4021 if (listFromMap == null || listFromMap.isEmpty()) {
4022 log.debug("failed to find properties ");
4023 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
4024 return responseFormat;
4026 for (PropertyDefinition prop : listFromMap) {
4027 String propName = prop.getName();
4028 if (!currPropertiesMap.containsKey(propName)) {
4029 currPropertiesMap.put(propName, prop);
4032 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
4033 for (List<UploadPropInfo> propertyList : propMap.values()) {
4035 UploadPropInfo propertyInfo = propertyList.get(0);
4036 String propName = propertyInfo.getName();
4037 if (!currPropertiesMap.containsKey(propName)) {
4038 log.debug("failed to find property {} ", propName);
4039 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
4040 return responseFormat;
4042 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
4043 ComponentInstanceProperty property = null;
4045 String value = null;
4046 List<GetInputValueDataDefinition> getInputs = null;
4047 boolean isValidate = true;
4048 if (propertyInfo.getValue() != null) {
4049 getInputs = propertyInfo.getGet_input();
4050 isValidate = getInputs == null || getInputs.isEmpty();
4052 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
4054 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
4056 String innerType = null;
4057 property = new ComponentInstanceProperty(curPropertyDef, value, null);
4059 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
4060 if (validatevalueEiter.isRight()) {
4061 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
4064 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
4065 // property.setUniqueId(uniqueId);
4066 property.setValue(validatevalueEiter.left().value());
4068 if (getInputs != null && !getInputs.isEmpty()) {
4069 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
4070 for (GetInputValueDataDefinition getInput : getInputs) {
4071 List<InputDefinition> inputs = resource.getInputs();
4072 if (inputs == null || inputs.isEmpty()) {
4073 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
4074 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4077 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
4078 if (!optional.isPresent()) {
4079 log.debug("Failed to find input {} ", getInput.getInputName());
4080 // @@TODO error message
4081 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4083 InputDefinition input = optional.get();
4084 getInput.setInputId(input.getUniqueId());
4085 getInputValues.add(getInput);
4087 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
4088 if (getInputIndex != null) {
4089 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
4090 if (!optional.isPresent()) {
4091 log.debug("Failed to find input {} ", getInputIndex.getInputName());
4092 // @@TODO error message
4093 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4095 InputDefinition inputIndex = optional.get();
4096 getInputIndex.setInputId(inputIndex.getUniqueId());
4097 getInputValues.add(getInputIndex);
4102 property.setGetInputValues(getInputValues);
4104 instPropList.add(property);
4105 // delete overriden property
4106 currPropertiesMap.remove(property.getName());
4108 // add rest of properties
4109 if (!currPropertiesMap.isEmpty()) {
4110 for (PropertyDefinition value : currPropertiesMap.values()) {
4111 instPropList.add(new ComponentInstanceProperty(value));
4114 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
4116 return componentsUtils.getResponseFormat(ActionStatus.OK);
4119 // US740820 Relate RIs according to capability name
4120 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4121 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
4125 return findAviableCapability(validReq, currentCapCompInstance);
4127 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
4130 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4131 CapabilityDefinition cap = null;
4132 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4133 if (!capMap.containsKey(validReq.getCapability())) {
4136 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
4137 if (!capByName.isPresent()) {
4140 cap = capByName.get();
4142 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4143 String leftOccurrences = cap.getLeftOccurrences();
4144 int left = Integer.parseInt(leftOccurrences);
4147 cap.setLeftOccurrences(String.valueOf(left));
4153 // TODO temporary fix - remove specific capability node validation -
4154 // String reqNode = validReq.getNode();
4155 // if (reqNode != null && !reqNode.isEmpty() &&
4156 // !cap.getCapabilitySources().contains(reqNode)) {
4159 // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
4160 // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
4161 // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
4167 private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
4168 CapabilityDefinition aviableCapForRel = null;
4169 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4170 if (capMap.containsKey(validReq.getCapability())) {
4171 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
4173 for (CapabilityDefinition cap : capList) {
4174 // TODO temporary fix - remove specific capability node
4175 // String reqNode = validReq.getNode();
4176 // if (reqNode != null && !reqNode.isEmpty()) {
4177 // if (!cap.getCapabilitySources().contains(reqNode)) {
4181 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4182 String leftOccurrences = cap.getLeftOccurrences();
4183 if (leftOccurrences == null) {
4184 leftOccurrences = cap.getMaxOccurrences();
4186 int left = Integer.parseInt(leftOccurrences);
4189 cap.setLeftOccurrences(String.valueOf(left));
4190 aviableCapForRel = cap;
4196 aviableCapForRel = cap;
4201 return aviableCapForRel;
4204 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
4205 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
4206 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
4207 RequirementDefinition validRegDef = null;
4209 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
4210 for (RequirementDefinition reqDef : entry.getValue()) {
4211 if (reqDef.getName().equals(regName)) {
4212 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4213 String leftOccurrences = reqDef.getLeftOccurrences();
4214 if (leftOccurrences == null) {
4215 leftOccurrences = reqDef.getMaxOccurrences();
4217 int left = Integer.parseInt(leftOccurrences);
4220 reqDef.setLeftOccurrences(String.valueOf(left));
4221 validRegDef = reqDef;
4227 validRegDef = reqDef;
4233 if (validRegDef != null) {
4238 for (RequirementDefinition reqDef : list) {
4239 if (reqDef.getName().equals(regName)) {
4240 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4241 String leftOccurrences = reqDef.getLeftOccurrences();
4242 if (leftOccurrences == null) {
4243 leftOccurrences = reqDef.getMaxOccurrences();
4245 int left = Integer.parseInt(leftOccurrences);
4248 reqDef.setLeftOccurrences(String.valueOf(left));
4249 validRegDef = reqDef;
4255 validRegDef = reqDef;
4261 if (validRegDef == null) {
4262 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4263 return Either.right(responseFormat);
4265 return Either.left(validRegDef);
4268 @SuppressWarnings("unchecked")
4269 public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
4271 Map<String, Object> mappedToscaTemplate;
4272 if(nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)){
4273 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
4277 //DE154502 Fail if duplicate key found in file
4278 mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
4280 } catch(ParserException e) {
4281 log.error("Failed to load yaml file {}", yamlFileName, e);
4282 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, yamlFileName, e.getMessage());
4283 return Either.right(responseFormat);
4286 Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
4287 if (toscaElementEither.isRight()) {
4288 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4289 return Either.right(responseFormat);
4292 Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4293 if (createInputsEither.isRight()) {
4294 ResponseFormat responseFormat = createInputsEither.right().value();
4295 return Either.right(responseFormat);
4298 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
4299 if (uploadResInstancesEither.isRight()) {
4300 ResponseFormat responseFormat = uploadResInstancesEither.right().value();
4301 return Either.right(responseFormat);
4304 Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4305 if (createGroupsFromYaml.isRight()) {
4306 ResponseFormat responseFormat = createGroupsFromYaml.right().value();
4307 return Either.right(responseFormat);
4310 ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
4311 parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
4312 parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
4313 parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
4315 return Either.left(parsedToscaYamlInfo);
4318 private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
4319 Map<String, Resource> nodeNamespaceMap) {
4321 Either<Resource, ResponseFormat> eitherResource = null;
4322 log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
4323 if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
4324 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4326 return Either.right(responseFormat);
4329 Map<String, Resource> existingnodeTypeMap = new HashMap<>();
4330 if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) {
4331 nodeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
4334 Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
4335 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
4336 while (nodesInfoValue.hasNext()) {
4337 log.debug("*************Going to create resource instances {}", yamlName);
4338 Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
4339 UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
4341 // updating type if the type is node type name - we need to take the
4343 log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
4344 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4345 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
4348 eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
4349 if (eitherResource.isRight()) {
4350 return eitherResource;
4352 Resource refResource = eitherResource.left().value();
4354 ComponentInstance componentInstance = new ComponentInstance();
4356 componentInstance.setComponentUid(refResource.getUniqueId());
4358 ComponentTypeEnum containerComponentType = resource.getComponentType();
4359 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
4361 if (containerNodeType.equals(NodeTypeEnum.Resource) && uploadComponentInstanceInfo.getCapabilities() != null) {
4362 Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4363 if (getValidComponentInstanceCapabilitiesRes.isRight()) {
4364 return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
4366 componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
4369 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
4370 log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4371 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4372 return Either.right(responseFormat);
4374 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
4375 componentInstance.setName(uploadComponentInstanceInfo.getName());
4376 componentInstance.setIcon(origResource.getIcon());
4378 resourcesInstancesMap.put(componentInstance, origResource);
4381 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
4383 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
4384 if (status != null && status != StorageOperationStatus.OK) {
4385 log.debug("Failed to add component instances to container component {}", resource.getName());
4386 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
4387 eitherResource = Either.right(responseFormat);
4388 return eitherResource;
4393 log.debug("*************Going to get resource {}", resource.getUniqueId());
4394 ComponentParametersView parametersView = new ComponentParametersView();
4395 parametersView.disableAll();
4396 parametersView.setIgnoreComponentInstances(false);
4397 parametersView.setIgnoreUsers(false);
4398 parametersView.setIgnoreInputs(false); // inputs are read when creating
4399 // property values on instances
4400 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
4401 log.debug("*************finished to get resource {}", resource.getUniqueId());
4402 if (eitherGerResource.isRight()) {
4403 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
4405 return Either.right(responseFormat);
4409 if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
4411 log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
4412 BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty");
4413 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4414 return Either.right(responseFormat);
4418 return Either.left(eitherGerResource.left().value());
4421 private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
4422 log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4423 Resource refResource = null;
4424 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4425 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
4427 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
4428 if (findResourceEither.isRight()) {
4429 log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4430 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
4431 return Either.right(responseFormat);
4433 refResource = findResourceEither.left().value();
4434 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
4436 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
4437 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4438 log.debug("validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState);
4439 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
4440 return Either.right(responseFormat);
4443 if (!ToscaUtils.isAtomicType(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
4444 log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
4445 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4446 return Either.right(responseFormat);
4448 return Either.left(refResource);
4451 private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) {
4452 Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
4453 Map<String, Object> substitutionMappings = null;
4454 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
4455 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
4456 Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
4457 if (eitherSubstitutionMappings.isLeft()) {
4458 substitutionMappings = eitherSubstitutionMappings.left().value();
4460 if (eitherNodesTemlates.isLeft()) {
4461 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
4463 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
4464 while (nodesNameValue.hasNext()) {
4465 Entry<String, Object> nodeNameValue = nodesNameValue.next();
4466 Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
4467 if (eitherNode.isRight()) {
4468 log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
4469 return Either.right(eitherNode.right().value());
4471 UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
4472 moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
4478 if (moduleComponentInstances.isEmpty()) {
4479 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
4480 return Either.right(responseFormat);
4486 @SuppressWarnings("unchecked")
4487 private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) {
4489 UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
4490 Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
4491 nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
4493 if (nodeTemplateJsonEntry.getValue() instanceof String) {
4494 String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
4495 nodeTemplateInfo.setType(nodeTemplateJsonString);
4496 } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
4497 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
4499 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4500 String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
4501 if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
4502 toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
4504 nodeTemplateInfo.setType(toscaResourceType);
4507 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4508 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4509 if (regResponse.isRight())
4510 return Either.right(regResponse.right().value());
4511 if (regResponse.left().value().size() > 0) {
4512 nodeTemplateInfo.setRequirements(regResponse.left().value());
4516 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4517 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4518 if (eitherCapRes.isRight())
4519 return Either.right(eitherCapRes.right().value());
4520 if (eitherCapRes.left().value().size() > 0) {
4521 nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
4524 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4525 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4526 if (regResponse.isRight())
4527 return Either.right(regResponse.right().value());
4528 if (regResponse.left().value().size() > 0) {
4529 nodeTemplateInfo.setProperties(regResponse.left().value());
4532 if (substitutionMappings != null) {
4533 if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4534 Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
4535 if (getCapNamesToUpdateRes.isRight())
4536 return Either.right(getCapNamesToUpdateRes.right().value());
4537 if (getCapNamesToUpdateRes.left().value().size() > 0) {
4538 nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
4541 if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4542 Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
4543 if (getReqNamesToUpdateRes.isRight())
4544 return Either.right(getReqNamesToUpdateRes.right().value());
4545 if (getReqNamesToUpdateRes.left().value().size() > 0) {
4546 nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
4552 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
4555 } catch (Exception e) {
4556 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
4557 log.debug("error when creating capability, message:{}", e.getMessage(), e);
4558 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
4564 private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) {
4565 Either<Map<String, String>, ResponseFormat> response;
4567 Map<String, String> namesToUpdate = elements.entrySet().stream().filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())).collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
4568 response = Either.left(namesToUpdate);
4569 } catch (Exception e) {
4570 log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName());
4571 response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4576 @SuppressWarnings("unchecked")
4577 private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
4578 Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
4579 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
4580 Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
4581 if (toscaProperties.isLeft()) {
4582 Map<String, Object> jsonProperties = toscaProperties.left().value();
4583 for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
4585 String propName = jsonPropObj.getKey();
4586 Object propValue = jsonPropObj.getValue();
4588 if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
4589 log.trace("Ignore property value {}.", propName);
4593 if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
4594 log.trace("Ignore property value {}.", propName);
4597 if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
4598 log.trace("Ignore property value {}.", propName);
4602 if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
4603 log.trace("Ignore property value {}.", propName);
4607 UploadPropInfo propertyDef = new UploadPropInfo();
4608 propertyDef.setValue(propValue);
4609 propertyDef.setName(propName);
4610 if (propValue instanceof Map) {
4611 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4612 propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
4615 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
4616 || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4617 createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
4620 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
4621 propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
4623 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
4624 propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
4626 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
4627 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
4629 propertyDef.setValue(propValue);
4631 } else if (propValue instanceof List) {
4632 List<Object> propValueList = (List<Object>) propValue;
4634 createInputPropList(propertyDef, propValueList);
4635 propertyDef.setValue(propValue);
4638 if (moduleProp.containsKey(propName)) {
4639 moduleProp.get(propName).add(propertyDef);
4641 List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
4642 list.add(propertyDef);
4643 moduleProp.put(propName, list);
4650 @SuppressWarnings("unchecked")
4651 private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
4652 for (Object objValue : propValueList) {
4654 if (objValue instanceof Map) {
4655 Map<String, Object> objMap = (Map<String, Object>) objValue;
4656 if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
4657 createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
4659 Set<String> keys = objMap.keySet();
4660 for (String key : keys) {
4661 Object value = objMap.get(key);
4662 if (value instanceof Map) {
4663 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4665 } else if (value instanceof List) {
4666 List<Object> propSubValueList = (List<Object>) value;
4668 createInputPropList(propertyDef, propSubValueList);
4674 } else if (objValue instanceof List) {
4675 List<Object> propSubValueList = (List<Object>) objValue;
4677 createInputPropList(propertyDef, propSubValueList);
4684 @SuppressWarnings("unchecked")
4685 private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
4687 if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4688 Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4689 GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
4690 List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
4691 if (getInputs == null) {
4692 getInputs = new ArrayList<GetInputValueDataDefinition>();
4694 if (getInput instanceof String) {
4696 getInputInfo.setInputName((String) getInput);
4697 getInputInfo.setPropName(propName);
4699 } else if (getInput instanceof List) {
4700 List<Object> getInputList = (List<Object>) getInput;
4701 getInputInfo.setPropName(propName);
4702 getInputInfo.setInputName((String) getInputList.get(0));
4703 if (getInputList.size() > 1) {
4704 Object indexObj = getInputList.get(1);
4705 if (indexObj instanceof Integer) {
4706 getInputInfo.setIndexValue((Integer) indexObj);
4707 } else if (indexObj instanceof Float) {
4708 int index = ((Float) indexObj).intValue();
4709 getInputInfo.setIndexValue(index);
4710 } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4711 Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4712 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
4713 getInputInfoIndex.setInputName((String) index);
4714 getInputInfoIndex.setPropName(propName);
4715 getInputInfo.setGetInputIndex(getInputInfoIndex);
4717 getInputInfo.setList(true);
4721 getInputs.add(getInputInfo);
4722 propertyDef.setGet_input(getInputs);
4723 propertyDef.setValue(propValue);
4725 Set<String> keys = propValue.keySet();
4726 for (String key : keys) {
4727 Object value = propValue.get(key);
4728 if (value instanceof Map) {
4729 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4731 } else if (value instanceof List) {
4732 List<Object> valueList = (List<Object>) value;
4733 for (Object o : valueList) {
4734 if (o instanceof Map) {
4735 createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
4748 * private boolean valueContainsStrReplace(Object propValue) {
4750 * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher =
4751 * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); }
4755 * private boolean valueContainsToken(Object propValue) {
4757 * 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 =
4763 private boolean valueContainsPattern(Pattern pattern, Object propValue) {
4765 log.debug("valueContainsToken value is {}", propValue);
4766 boolean result = false;
4767 if (propValue != null) {
4768 log.trace("valueContainspattern value is {}", propValue.getClass());
4769 Matcher matcher = pattern.matcher(propValue.toString());
4770 result = matcher.find();
4777 @SuppressWarnings("unchecked")
4778 private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4779 Map<String, List<UploadCapInfo>> moduleCap = new HashMap<String, List<UploadCapInfo>>();
4780 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
4781 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4782 if (toscaRequirements.isLeft()) {
4783 List<Object> jsonCapabilities = toscaRequirements.left().value();
4785 for (Object jsonCapObj : jsonCapabilities) {
4787 Map<String, Object> capJsonWrapper = (Map<String, Object>) jsonCapObj;
4788 String capName = capJsonWrapper.keySet().iterator().next();
4789 Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJsonWrapper.get(capName));
4790 if (eitherCap.isRight()) {
4791 log.info("error when creating Requirement:{}, for node:{}", capName, nodeTemplateInfo);
4792 return Either.right(eitherCap.right().value());
4794 UploadCapInfo requirementDef = eitherCap.left().value();
4795 requirementDef.setName(capName);
4796 if (moduleCap.containsKey(capName)) {
4797 moduleCap.get(capName).add(requirementDef);
4799 List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
4800 list.add(requirementDef);
4801 moduleCap.put(capName, list);
4809 @SuppressWarnings("unchecked")
4810 private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4811 Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
4812 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
4813 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4814 if (toscaRequirements.isLeft()) {
4815 List<Object> jsonRequirements = toscaRequirements.left().value();
4817 for (Object jsonRequirementObj : jsonRequirements) {
4819 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
4820 String requirementName = requirementJsonWrapper.keySet().iterator().next();
4821 Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJsonWrapper.get(requirementName));
4822 if (eitherRequirement.isRight()) {
4823 log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
4824 return Either.right(eitherRequirement.right().value());
4826 UploadReqInfo requirementDef = eitherRequirement.left().value();
4827 requirementDef.setName(requirementName);
4828 if (moduleRequirements.containsKey(requirementName)) {
4829 moduleRequirements.get(requirementName).add(requirementDef);
4831 List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
4832 list.add(requirementDef);
4833 moduleRequirements.put(requirementName, list);
4841 @SuppressWarnings("unchecked")
4842 private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
4843 UploadCapInfo capTemplateInfo = new UploadCapInfo();
4844 Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
4846 if (capObject instanceof String) {
4847 String nodeTemplateJsonString = (String) capObject;
4848 capTemplateInfo.setNode(nodeTemplateJsonString);
4849 } else if (capObject instanceof Map) {
4850 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
4852 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4853 capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4855 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4856 capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4858 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
4859 Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
4860 if (validSourceTypesRes.isLeft()) {
4861 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList()));
4864 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4865 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4866 if (regResponse.isRight())
4867 return Either.right(regResponse.right().value());
4868 if (!regResponse.left().value().isEmpty()) {
4869 List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
4870 regResponse.left().value().values().forEach(list -> properties.addAll(list));
4871 if (!properties.isEmpty())
4872 capTemplateInfo.setProperties(properties);
4879 @SuppressWarnings("unchecked")
4880 private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
4882 UploadReqInfo regTemplateInfo = new UploadReqInfo();
4883 Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
4885 if (regObject instanceof String) {
4886 String nodeTemplateJsonString = (String) regObject;
4887 regTemplateInfo.setNode(nodeTemplateJsonString);
4888 } else if (regObject instanceof Map) {
4889 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
4891 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4892 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4894 // US740820 Relate RIs according to capability name
4895 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
4896 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
4902 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) {
4904 Either<Resource, ResponseFormat> result = null;
4906 if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())){
4907 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4908 if(result.isRight()){
4911 resource = result.left().value();
4913 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
4914 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
4915 result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
4918 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
4919 } catch (Exception e) {
4920 log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName());
4921 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4923 if (result == null || result.isRight()) {
4924 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4925 if (inTransaction == false) {
4926 log.debug("operation failed. do rollback");
4927 titanDao.rollback();
4929 } else if (inTransaction == false) {
4930 log.debug("operation success. do commit");
4936 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4937 Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
4938 if (result.isLeft()) {
4939 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
4941 if (result.isLeft()) {
4942 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
4947 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4948 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4954 * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
4957 * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
4958 * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
4961 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo) {
4963 // check if resource already exist
4964 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
4965 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4968 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4970 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
4971 if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
4972 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
4975 StorageOperationStatus status = latestByName.right().value();
4976 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4977 log.debug("resource already exist {}. status={}", resource.getName(), status);
4978 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
4979 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4980 result = Either.right(responseFormat);
4986 else if (latestByName.isLeft()) {
4987 result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock);
4992 StorageOperationStatus status = latestByName.right().value();
4993 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
4994 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
4995 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4996 result = Either.right(responseFormat);
5002 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
5003 log.debug("resource with name {} does not exist. create new resource", resource.getName());
5004 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
5005 if (response.isRight()) {
5006 return Either.right(response.right().value());
5008 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
5009 if (createResponse.isRight()) {
5010 return Either.right(createResponse.right().value());
5012 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
5013 ASDCKpiApi.countImportResourcesKPI();
5014 return Either.left(resourcePair);
5019 public boolean isResourceExist(String resourceName) {
5020 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
5021 return latestByName.isLeft();
5024 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock) {
5025 String lockedResourceId = oldResource.getUniqueId();
5026 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState());
5027 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
5030 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import");
5031 if (lockResult.isRight()) {
5032 return Either.right(lockResult.right().value());
5036 Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false);
5037 if (prepareResourceForUpdate.isRight()) {
5038 ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
5039 log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage());
5040 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5041 result = Either.right(prepareResourceForUpdate.right().value());
5044 oldResource = prepareResourceForUpdate.left().value();
5046 mergeOldResourceMetadataWithNew(oldResource, newResource);
5048 Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction);
5049 if (validateFieldsResponse.isRight()) {
5050 result = Either.right(validateFieldsResponse.right().value());
5054 // contact info normalization
5055 newResource.setContactId(newResource.getContactId().toLowerCase());
5056 // non-updatable fields
5057 newResource.setCreatorUserId(user.getUserId());
5058 newResource.setCreatorFullName(user.getFullName());
5059 newResource.setLastUpdaterUserId(user.getUserId());
5060 newResource.setLastUpdaterFullName(user.getFullName());
5061 newResource.setUniqueId(oldResource.getUniqueId());
5062 newResource.setVersion(oldResource.getVersion());
5063 newResource.setInvariantUUID(oldResource.getInvariantUUID());
5064 newResource.setLifecycleState(oldResource.getLifecycleState());
5065 newResource.setUUID(oldResource.getUUID());
5066 newResource.setNormalizedName(oldResource.getNormalizedName());
5067 newResource.setSystemName(oldResource.getSystemName());
5068 if (oldResource.getCsarUUID() != null) {
5069 newResource.setCsarUUID(oldResource.getCsarUUID());
5071 if (oldResource.getImportedToscaChecksum() != null) {
5072 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
5074 newResource.setAbstract(oldResource.isAbstract());
5076 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
5077 newResource.setDerivedFrom(oldResource.getDerivedFrom());
5079 // TODO rhalili: handle artifacts here (delete from old resource and
5081 // TODO rbetzer: remove after migration - in case of resources
5082 // created without tosca artifacts - add the placeholders
5083 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
5084 setToscaArtifactsPlaceHolders(newResource, user);
5086 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
5088 if (overrideResource.isRight()) {
5089 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
5090 componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5091 result = Either.right(responseFormat);
5095 log.debug("Resource updated successfully!!!");
5096 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
5097 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5099 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
5100 result = Either.left(resourcePair);
5103 if (result == null || result.isRight()) {
5104 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
5105 log.debug("operation failed. do rollback");
5106 titanDao.rollback();
5107 } else if (inTransaction == false) {
5108 log.debug("operation success. do commit");
5111 if (needLock == true) {
5112 log.debug("unlock resource {}", lockedResourceId);
5113 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
5120 * Merge old resource with new. Keep old category and vendor name without change
5122 * @param oldResource
5123 * @param newResource
5125 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
5127 // keep old category and vendor name without change
5128 // merge the rest of the resource metadata
5129 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
5130 newResource.setTags(oldResource.getTags());
5133 if (newResource.getDescription() == null) {
5134 newResource.setDescription(oldResource.getDescription());
5137 if (newResource.getVendorRelease() == null) {
5138 newResource.setVendorRelease(oldResource.getVendorRelease());
5141 if (newResource.getResourceVendorModelNumber() == null) {
5142 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
5145 if (newResource.getContactId() == null) {
5146 newResource.setContactId(oldResource.getContactId());
5149 newResource.setCategories(oldResource.getCategories());
5150 newResource.setVendorName(oldResource.getVendorName());
5153 private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) {
5155 Either<Resource, ResponseFormat> result = Either.left(latestResource);
5156 // check if user can edit resource
5157 if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
5159 Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
5160 result = changeState;
5166 public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
5168 Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
5169 if (eitherValidation.isRight()) {
5170 return Either.right(eitherValidation.right().value());
5173 eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
5174 if (eitherValidation.isRight()) {
5175 return Either.right(eitherValidation.right().value());
5177 eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
5178 if (eitherValidation.isRight()) {
5179 return Either.right(eitherValidation.right().value());
5181 eitherValidation = validateResourceType(user, resource, actionEnum);
5182 if (eitherValidation.isRight()) {
5183 return Either.right(eitherValidation.right().value());
5186 resource.setCreatorUserId(user.getUserId());
5187 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
5188 resource.setContactId(resource.getContactId().toLowerCase());
5189 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ToscaUtils.isAtomicType(resource)) {
5190 String resourceSystemName;
5191 if(csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())){
5192 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
5194 resourceSystemName = resource.getSystemName();
5196 resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
5199 // Generate invariant UUID - must be here and not in operation since it
5200 // should stay constant during clone
5202 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
5203 resource.setInvariantUUID(invariantUUID);
5205 return Either.left(resource);
5208 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
5209 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5210 if (resource.getResourceType() == null) {
5211 log.debug("Invalid resource type for resource");
5212 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5213 eitherResult = Either.right(errorResponse);
5214 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5216 return eitherResult;
5219 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
5220 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5221 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
5222 log.debug("validate interface lifecycle Types Exist");
5223 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
5224 while (intItr.hasNext() && eitherResult.isLeft()) {
5225 InterfaceDefinition interfaceDefinition = intItr.next();
5226 String intType = interfaceDefinition.getUniqueId();
5227 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
5228 if (eitherCapTypeFound.isRight()) {
5229 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5230 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
5231 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
5232 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
5233 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
5236 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
5237 eitherResult = Either.right(errorResponse);
5238 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5243 return eitherResult;
5246 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5248 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5249 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
5250 log.debug("validate capability Types Exist - capabilities section");
5252 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
5254 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
5255 if (eitherResult.isRight()) {
5256 return Either.right(eitherResult.right().value());
5261 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
5262 log.debug("validate capability Types Exist - requirements section");
5263 for (String type : resource.getRequirements().keySet()) {
5264 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
5265 if (eitherResult.isRight()) {
5266 return Either.right(eitherResult.right().value());
5271 return eitherResult;
5274 // @param typeObject- the object to which the validation is done
5275 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
5276 boolean inTransaction) {
5277 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
5278 if (eitherCapTypeFound.isRight()) {
5279 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5280 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
5281 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
5282 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5284 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
5285 ResponseFormat errorResponse = null;
5287 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
5289 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
5290 eitherResult = Either.right(errorResponse);
5291 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5293 return eitherResult;
5296 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
5297 Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
5298 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
5299 if (eitherCapTypeFound.isRight()) {
5300 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5301 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
5302 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
5303 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5305 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
5306 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
5307 eitherResult = Either.right(errorResponse);
5308 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5310 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
5311 if (capabilityTypeDefinition.getProperties() != null) {
5312 for (CapabilityDefinition capDef : typeEntry.getValue()) {
5313 List<ComponentInstanceProperty> properties = capDef.getProperties();
5314 if (properties == null || properties.isEmpty()) {
5315 properties = new ArrayList<ComponentInstanceProperty>();
5316 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5317 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
5318 properties.add(newProp);
5321 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5322 PropertyDefinition porpFromDef = prop.getValue();
5323 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
5324 for (ComponentInstanceProperty cip : properties) {
5325 if (!cip.getName().equals(porpFromDef.getName())) {
5326 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
5327 propsToAdd.add(newProp);
5330 if (!propsToAdd.isEmpty()) {
5331 properties.addAll(propsToAdd);
5335 capDef.setProperties(properties);
5338 return eitherResult;
5341 public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5344 // lock new resource name in order to avoid creation resource with same
5346 if (inTransaction == false) {
5347 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
5348 if (lockResult.isRight()) {
5349 ResponseFormat responseFormat = lockResult.right().value();
5350 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
5351 return Either.right(responseFormat);
5354 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
5357 if (resource.deriveFromGeneric()) {
5358 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
5359 if (genericResourceEither.isRight())
5360 return genericResourceEither;
5361 if (resource.shouldGenerateInputs())
5362 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
5365 Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
5366 if (respStatus.isLeft()) {
5367 auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams);
5368 ASDCKpiApi.countCreatedResourcesKPI();
5370 componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
5374 if (inTransaction == false) {
5375 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
5380 private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5381 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
5382 componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams);
5385 private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
5386 // validate resource name uniqueness
5387 log.debug("validate resource name");
5388 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
5389 if (eitherValidation.isRight()) {
5390 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
5391 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
5392 return Either.right(errorResponse);
5394 if (eitherValidation.left().value()) {
5395 log.debug("resource with name: {}, already exists", resource.getName());
5396 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5397 return Either.right(errorResponse);
5400 log.debug("send resource {} to dao for create", resource.getName());
5402 createArtifactsPlaceHolderData(resource, user);
5408 log.debug("enrich resource with creator, version and state");
5409 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
5410 resource.setVersion(INITIAL_VERSION);
5411 resource.setHighestVersion(true);
5412 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
5413 resource.setAbstract(false);
5416 Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
5417 if (createToscaElement.isLeft()) {
5418 return Either.left(createToscaElement.left().value());
5421 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
5423 return Either.right(responseFormat);
5426 private void createArtifactsPlaceHolderData(Resource resource, User user) {
5427 // create mandatory artifacts
5429 // TODO it must be removed after that artifact uniqueId creation will be
5430 // moved to ArtifactOperation
5431 // String resourceUniqueId =
5432 // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
5433 // resource.getResourceVersion());
5435 setInformationalArtifactsPlaceHolder(resource, user);
5436 setDeploymentArtifactsPlaceHolder(resource, user);
5437 setToscaArtifactsPlaceHolders(resource, user);
5440 @SuppressWarnings("unchecked")
5442 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
5443 Resource resource = (Resource) component;
5444 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
5445 if (artifactMap == null) {
5446 artifactMap = new HashMap<String, ArtifactDefinition>();
5448 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts();
5449 if (deploymentResourceArtifacts != null) {
5450 Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
5451 while (iterator.hasNext()) {
5452 Entry<String, Object> currEntry = iterator.next();
5453 boolean shouldCreateArtifact = true;
5454 Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
5455 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
5456 if (object != null) {
5457 List<String> artifactTypes = (List<String>) object;
5458 if (!artifactTypes.contains(resource.getResourceType().name())) {
5459 shouldCreateArtifact = false;
5463 log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey());
5465 if (shouldCreateArtifact) {
5466 if (artifactsBusinessLogic != null) {
5467 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT);
5468 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
5469 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5474 resource.setDeploymentArtifacts(artifactMap);
5477 @SuppressWarnings("unchecked")
5478 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
5479 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
5480 if (artifactMap == null) {
5481 artifactMap = new HashMap<String, ArtifactDefinition>();
5483 String resourceUniqueId = resource.getUniqueId();
5484 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
5485 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
5486 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
5487 List<CategoryDefinition> categories = resource.getCategories();
5488 boolean isCreateArtifact = true;
5489 if (exludeResourceCategory != null) {
5490 String category = categories.get(0).getName();
5491 for (String exlude : exludeResourceCategory) {
5492 if (exlude.equalsIgnoreCase(category)) {
5493 isCreateArtifact = false;
5499 if (isCreateArtifact && exludeResourceType != null) {
5500 String resourceType = resource.getResourceType().name();
5501 for (String type : exludeResourceType) {
5502 if (type.equalsIgnoreCase(resourceType)) {
5503 isCreateArtifact = false;
5510 if (informationalResourceArtifacts != null && isCreateArtifact) {
5511 Set<String> keys = informationalResourceArtifacts.keySet();
5512 for (String informationalResourceArtifactName : keys) {
5513 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
5514 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
5515 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5519 resource.setArtifacts(artifactMap);
5529 public ResponseFormat deleteResource(String resourceId, User user) {
5530 ResponseFormat responseFormat;
5531 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5532 if (eitherCreator.isRight()) {
5533 return eitherCreator.right().value();
5536 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
5537 if (resourceStatus.isRight()) {
5538 log.debug("failed to get resource {}", resourceId);
5539 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
5542 Resource resource = resourceStatus.left().value();
5544 StorageOperationStatus result = StorageOperationStatus.OK;
5545 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
5546 if (lockResult.isRight()) {
5547 result = StorageOperationStatus.GENERAL_ERROR;
5548 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5553 result = markComponentToDelete(resource);
5554 if (result.equals(StorageOperationStatus.OK)) {
5555 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5557 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5558 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5560 return responseFormat;
5563 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5564 log.warn("operation failed. do rollback");
5565 titanDao.rollback();
5567 log.debug("operation success. do commit");
5570 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
5575 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
5576 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5577 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5578 if (eitherCreator.isRight()) {
5579 return eitherCreator.right().value();
5582 // Resource resource = null;
5583 Resource resource = null;
5584 StorageOperationStatus result = StorageOperationStatus.OK;
5587 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
5588 if (resourceStatus.isRight()) {
5589 log.debug("failed to get resource {} version {}", resourceName, version);
5590 return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
5593 resource = resourceStatus.left().value();
5596 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5597 log.warn("operation failed. do rollback");
5598 titanDao.rollback();
5599 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5600 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
5602 log.debug("operation success. do commit");
5606 if (resource != null) {
5607 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
5608 if (lockResult.isRight()) {
5609 result = StorageOperationStatus.GENERAL_ERROR;
5610 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5613 result = markComponentToDelete(resource);
5614 if (!result.equals(StorageOperationStatus.OK)) {
5615 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5616 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5617 return responseFormat;
5621 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5622 log.warn("operation failed. do rollback");
5623 titanDao.rollback();
5625 log.debug("operation success. do commit");
5628 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
5631 return responseFormat;
5634 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
5637 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
5638 if (eitherCreator.isRight()) {
5639 return Either.right(eitherCreator.right().value());
5643 // IResourceOperation dataModel = getResourceOperation();
5644 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
5645 if (storageStatus.isRight()) {
5646 log.debug("failed to get resource by id {}", resourceId);
5647 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
5649 if(!(storageStatus.left().value() instanceof Resource)){
5650 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
5652 return Either.left(storageStatus.left().value());
5656 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
5658 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
5659 if (resp.isRight()) {
5660 return Either.right(resp.right().value());
5663 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
5664 if (getResource.isRight()) {
5665 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
5666 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
5668 return Either.left(getResource.left().value());
5672 * updateResourceMetadata
5674 * @param user - modifier data (userId)
5675 * @param inTransaction TODO
5676 * @param resourceIdToUpdate - the resource identifier
5677 * @param newResource
5678 * @return Either<Resource, responseFormat>
5680 public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
5682 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
5683 if (resp.isRight()) {
5684 return Either.right(resp.right().value());
5687 // IResourceOperation dataModel = getResourceOperation();
5688 log.debug("Get resource with id {}", resourceIdToUpdate);
5689 boolean needToUnlock = false;
5690 boolean rollbackNeeded = true;
5693 // Either<Resource, StorageOperationStatus> storageStatus =
5694 // dataModel.getResource_tx(resourceIdToUpdate, false);
5695 if (currentResource == null) {
5696 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
5697 if (storageStatus.isRight()) {
5698 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5701 currentResource = storageStatus.left().value();
5703 // verify that resource is checked-out and the user is the last
5705 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
5706 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
5710 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5711 if (!lockResult.equals(StorageOperationStatus.OK)) {
5712 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
5713 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
5714 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
5715 return Either.right(responseFormat);
5718 needToUnlock = true;
5720 // critical section starts here
5721 // convert json to object
5723 // Update and updated resource must have a non-empty "derivedFrom"
5725 // This code is not called from import resources, because of root
5726 // VF "derivedFrom" should be null (or ignored)
5727 if (ToscaUtils.isAtomicType(currentResource)) {
5728 Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
5729 if (derivedFromNotEmptyEither.isRight()) {
5730 log.debug("for updated resource {}, derived from field is empty", newResource.getName());
5731 return Either.right(derivedFromNotEmptyEither.right().value());
5734 derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
5735 if (derivedFromNotEmptyEither.isRight()) {
5736 log.debug("for current resource {}, derived from field is empty", currentResource.getName());
5737 return Either.right(derivedFromNotEmptyEither.right().value());
5740 newResource.setDerivedFrom(null);
5743 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true);
5744 if (dataModelResponse.isRight()) {
5745 log.debug("failed to update resource metadata!!!");
5746 rollbackNeeded = true;
5747 return Either.right(dataModelResponse.right().value());
5750 log.debug("Resource metadata updated successfully!!!");
5751 rollbackNeeded = false;
5752 return Either.left(dataModelResponse.left().value());
5755 if (!inTransaction) {
5756 if (rollbackNeeded) {
5757 titanDao.rollback();
5764 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5769 private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){
5770 if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){
5771 if (log.isInfoEnabled())
5772 log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" );
5773 return Either.right(false);
5775 List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList());
5776 for ( GroupDefinition group : list) {
5777 if ( group!=null && group.isSamePrefix( replacePattern ) ){
5778 String prefix = group.getName().substring( 0, replacePattern.length() );
5779 String newGroupName = group.getName().replaceFirst(prefix , with);
5780 group.setName(newGroupName);
5781 //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id
5782 //group.setUniqueId(newUid);
5785 return Either.left(list);
5788 private boolean isComponentNameChanged(Resource newResource,Resource oldResource){
5789 if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional
5790 String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5791 String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5792 return !oldName.equals(futureName);
5797 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
5798 //region -> Update groups name for newResource
5799 if ( isComponentNameChanged( currentResource , newResource) ){
5800 String replacePattern = Optional.ofNullable( //get currentResource name from metadata
5801 Optional.ofNullable( Optional.ofNullable( currentResource )
5802 .orElse(null).getComponentMetadataDefinition() )
5803 .orElse(null).getMetadataDataDefinition() )
5804 .orElse(null).getName();
5805 String with = Optional.ofNullable( //get newResource name from metadata
5806 Optional.ofNullable( Optional.ofNullable( newResource )
5807 .orElse(null).getComponentMetadataDefinition() )
5808 .orElse(null).getMetadataDataDefinition() )
5809 .orElse(null).getName();
5810 if ( with != null && replacePattern != null ){
5811 Either<List<GroupDefinition>,Boolean> result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups());
5812 if (result.isLeft())
5813 newResource.setGroups( (List<GroupDefinition>)result.left().value() );
5818 Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
5819 if (validateResourceFields.isRight()) {
5820 return Either.right(validateResourceFields.right().value());
5822 // Setting last updater and uniqueId
5823 newResource.setContactId(newResource.getContactId().toLowerCase());
5824 newResource.setLastUpdaterUserId(user.getUserId());
5825 newResource.setUniqueId(resourceIdToUpdate);
5826 // Cannot set highest version through UI
5827 newResource.setHighestVersion(currentResource.isHighestVersion());
5828 newResource.setCreationDate(currentResource.getCreationDate());
5830 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
5832 if (processUpdateOfDerivedFrom.isRight()) {
5833 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
5834 return Either.right(processUpdateOfDerivedFrom.right().value());
5837 log.debug("send resource {} to dao for update", newResource.getUniqueId());
5838 if (newResource!=null && newResource.getGroups()!=null){
5839 for ( GroupDefinition group : newResource.getGroups() ){
5840 if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null)
5841 groupBusinessLogic.validateAndUpdateGroupMetadata(
5842 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() ,
5844 ComponentTypeEnum.RESOURCE_INSTANCE,
5850 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
5852 if (dataModelResponse.isRight()) {
5853 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
5854 return Either.right(responseFormat);
5855 } else if (dataModelResponse.left().value() == null) {
5856 log.debug("No response from updateResource");
5857 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5859 return Either.left(dataModelResponse.left().value());
5863 * validateResourceFieldsBeforeCreate
5865 * @param user - modifier data (userId)
5866 * @param dataModel - IResourceOperation for resource crud
5867 * @param resource - Resource object to validate
5868 * @return Either<Boolean, ErrorResponse>
5870 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5871 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
5872 if (componentsFieldsValidation.isRight()) {
5873 return componentsFieldsValidation;
5879 * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5881 * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5886 * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5891 * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5894 // validate category
5895 log.debug("validate category");
5896 Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
5897 if (eitherValidation.isRight()) {
5898 return eitherValidation;
5901 // validate vendor name & release & model number
5902 log.debug("validate vendor name");
5903 eitherValidation = validateVendorName(user, resource, actionEnum);
5904 if (eitherValidation.isRight()) {
5905 return eitherValidation;
5908 log.debug("validate vendor release");
5909 eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
5910 if (eitherValidation.isRight()) {
5911 return eitherValidation;
5914 log.debug("validate resource vendor model number");
5915 eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
5916 if (eitherValidation.isRight()) {
5917 return eitherValidation;
5920 // validate contact info
5922 * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5926 log.debug("validate cost");
5927 eitherValidation = validateCost(user, resource, actionEnum);
5928 if (eitherValidation.isRight()) {
5929 return eitherValidation;
5932 // validate licenseType
5933 log.debug("validate licenseType");
5934 eitherValidation = validateLicenseType(user, resource, actionEnum);
5935 if (eitherValidation.isRight()) {
5936 return eitherValidation;
5939 // validate template (derived from)
5940 log.debug("validate derived from");
5941 if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
5942 resource.setDerivedFrom(null);
5944 eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
5945 if (eitherValidation.isRight()) {
5946 return Either.right(eitherValidation.right().value());
5949 // warn about non-updatable fields
5950 checkComponentFieldsForOverrideAttempt(resource);
5951 String currentCreatorFullName = resource.getCreatorFullName();
5952 if (currentCreatorFullName != null) {
5953 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5956 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
5957 if (currentLastUpdaterFullName != null) {
5958 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5961 Long currentLastUpdateDate = resource.getLastUpdateDate();
5962 if (currentLastUpdateDate != null) {
5963 log.warn("Resource last update date is automatically set and cannot be updated");
5966 Boolean currentAbstract = resource.isAbstract();
5967 if (currentAbstract != null) {
5968 log.warn("Resource abstract is automatically set and cannot be updated");
5971 return Either.left(true);
5975 * validateResourceFieldsBeforeUpdate
5977 * @param currentResource - Resource object to validate
5978 * @return Either<Boolean, ErrorResponse>
5980 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
5982 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5984 // validate resource name
5985 log.debug("validate resource name before update");
5986 Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified);
5987 if (eitherValidation.isRight()) {
5988 return eitherValidation;
5991 // validate description
5992 log.debug("validate description before update");
5993 eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
5994 if (eitherValidation.isRight()) {
5995 return eitherValidation;
5998 log.debug("validate icon before update");
5999 eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
6000 if (eitherValidation.isRight()) {
6001 return eitherValidation;
6004 log.debug("validate tags before update");
6005 eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
6006 if (eitherValidation.isRight()) {
6007 return eitherValidation;
6010 log.debug("validate vendor name before update");
6011 eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
6012 if (eitherValidation.isRight()) {
6013 return eitherValidation;
6016 log.debug("validate resource vendor model number before update");
6017 eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
6018 if (eitherValidation.isRight()) {
6019 return eitherValidation;
6023 log.debug("validate vendor release before update");
6024 eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
6025 if (eitherValidation.isRight()) {
6026 return eitherValidation;
6029 log.debug("validate contact info before update");
6030 eitherValidation = validateContactId(null, updateInfoResource, null);
6031 if (eitherValidation.isRight()) {
6032 return eitherValidation;
6035 log.debug("validate derived before update");
6036 eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
6037 if (eitherValidation.isRight()) {
6038 return eitherValidation;
6041 log.debug("validate category before update");
6042 eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
6043 if (eitherValidation.isRight()) {
6044 return eitherValidation;
6047 // warn about non-updatable fields
6048 String currentResourceVersion = currentResource.getVersion();
6049 String updatedResourceVersion = updateInfoResource.getVersion();
6051 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
6052 log.warn("Resource version is automatically set and cannot be updated");
6055 String currentCreatorUserId = currentResource.getCreatorUserId();
6056 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
6058 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
6059 log.warn("Resource Creator UserId is automatically set and cannot be updated");
6062 String currentCreatorFullName = currentResource.getCreatorFullName();
6063 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
6065 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
6066 log.warn("Resource Creator fullname is automatically set and cannot be updated");
6069 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
6070 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
6072 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
6073 log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
6076 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
6077 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
6079 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
6080 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
6083 Long currentCreationDate = currentResource.getCreationDate();
6084 Long updatedCreationDate = updateInfoResource.getCreationDate();
6086 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
6087 log.warn("Resource Creation date is automatically set and cannot be updated");
6090 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
6091 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
6093 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
6094 log.warn("Resource last update date is automatically set and cannot be updated");
6097 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
6098 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
6100 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
6101 log.warn("Resource lifecycle state date is automatically set and cannot be updated");
6104 Boolean currentAbstract = currentResource.isAbstract();
6105 Boolean updatedAbstract = updateInfoResource.isAbstract();
6107 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
6108 log.warn("Resource abstract is automatically set and cannot be updated");
6111 Boolean currentHighestVersion = currentResource.isHighestVersion();
6112 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
6114 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
6115 log.warn("Resource highest version is automatically set and cannot be updated");
6118 String currentUuid = currentResource.getUUID();
6119 String updatedUuid = updateInfoResource.getUUID();
6121 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
6122 log.warn("Resource UUID is automatically set and cannot be updated");
6125 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
6126 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
6128 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
6129 log.warn("Resource Type cannot be updated");
6132 updateInfoResource.setResourceType(currentResource.getResourceType());
6134 String currentInvariantUuid = currentResource.getInvariantUUID();
6135 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
6137 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
6138 log.warn("Resource invariant UUID is automatically set and cannot be updated");
6139 updateInfoResource.setInvariantUUID(currentInvariantUuid);
6141 return Either.left(true);
6145 * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName();
6147 * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
6148 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); }
6150 * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.
6151 * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat);
6154 * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME,
6155 * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName(
6156 * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ;
6158 * return Either.left(true); }
6161 private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6162 String resourceNameUpdated = updateInfoResource.getName();
6163 String resourceNameCurrent = currentResource.getName();
6164 if (!resourceNameCurrent.equals(resourceNameUpdated)) {
6165 if (!hasBeenCertified) {
6166 Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null);
6167 if (validateResourceNameResponse.isRight()) {
6168 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6169 return Either.right(errorResponse);
6171 validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
6172 if (validateResourceNameResponse.isRight()) {
6173 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6174 return Either.right(errorResponse);
6176 currentResource.setName(resourceNameUpdated);
6177 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
6178 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
6181 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
6182 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
6183 return Either.right(errorResponse);
6186 return Either.left(true);
6189 private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6190 String iconUpdated = updateInfoResource.getIcon();
6191 String iconCurrent = currentResource.getIcon();
6192 if (!iconCurrent.equals(iconUpdated)) {
6193 if (!hasBeenCertified) {
6194 Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
6195 if (validateIcon.isRight()) {
6196 ResponseFormat errorResponse = validateIcon.right().value();
6197 return Either.right(errorResponse);
6200 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
6201 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
6202 return Either.right(errorResponse);
6205 return Either.left(true);
6208 private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6209 String vendorNameUpdated = updateInfoResource.getVendorName();
6210 String vendorNameCurrent = currentResource.getVendorName();
6211 if (!vendorNameCurrent.equals(vendorNameUpdated)) {
6212 if (!hasBeenCertified) {
6213 Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
6214 if (validateVendorName.isRight()) {
6215 ResponseFormat errorResponse = validateVendorName.right().value();
6216 return Either.right(errorResponse);
6219 log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated);
6220 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
6221 return Either.right(errorResponse);
6224 return Either.left(true);
6227 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
6228 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
6229 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
6230 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
6231 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null);
6232 if (validateResourceVendorModelNumber.isRight()) {
6233 ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
6234 return Either.right(errorResponse);
6237 return Either.left(true);
6240 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
6241 Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
6242 if (validateCategoryName.isRight()) {
6243 ResponseFormat errorResponse = validateCategoryName.right().value();
6244 return Either.right(errorResponse);
6246 if (hasBeenCertified) {
6247 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
6248 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
6249 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
6250 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
6251 if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
6252 log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
6253 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
6254 return Either.right(errorResponse);
6257 return Either.left(true);
6260 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6262 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
6263 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
6264 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
6265 log.trace("Update normative types");
6266 return Either.left(true);
6269 String derivedFromCurrent = currentDerivedFrom.get(0);
6270 String derivedFromUpdated = updatedDerivedFrom.get(0);
6272 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
6273 if (!hasBeenCertified) {
6274 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
6275 if (validateDerivedFromExistsEither.isRight()) {
6276 return validateDerivedFromExistsEither;
6279 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
6281 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
6282 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
6283 return validateDerivedFromExtending;
6287 // For derived from, we must know whether it was actually changed,
6288 // otherwise we must do no action.
6289 // Due to changes it inflicts on data model (remove artifacts,
6290 // properties...), it's not like a flat field which can be
6291 // overwritten if not changed.
6292 // So we must indicate that derived from is not changed
6293 updateInfoResource.setDerivedFrom(null);
6295 return Either.left(true);
6298 private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
6300 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
6301 return Either.left(true);
6304 // IResourceOperation resourceOperation = getResourceOperation();
6306 String templateName = resource.getDerivedFrom().get(0);
6308 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
6309 if (dataModelResponse.isRight()) {
6310 StorageOperationStatus storageStatus = dataModelResponse.right().value();
6311 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
6312 log.debug("request to data model failed with error: {}", storageStatus.name());
6313 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
6314 log.trace("audit before sending response");
6315 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6316 return Either.right(responseFormat);
6317 } else if (!dataModelResponse.left().value()) {
6318 log.info("resource template with name: {}, does not exists", templateName);
6319 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
6320 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6322 return Either.right(responseFormat);
6325 return Either.left(true);
6328 // Tal G for extending inheritance US815447
6329 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
6330 // If updated resource is not deriving, should fail validation
6332 * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6334 // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
6336 * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6338 String currentTemplateName = currentResource.getDerivedFrom().get(0);
6339 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
6341 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
6342 if (dataModelResponse.isRight()) {
6343 StorageOperationStatus storageStatus = dataModelResponse.right().value();
6344 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
6345 log.debug("request to data model failed with error: {}", storageStatus.name());
6346 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
6347 log.trace("audit before sending response");
6348 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6349 return Either.right(responseFormat);
6352 if (!dataModelResponse.left().value()) {
6353 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
6354 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
6355 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6357 return Either.right(responseFormat);
6360 return Either.left(true);
6363 public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
6364 log.debug("validate resource derivedFrom field");
6365 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
6366 log.info("derived from (template) field is missing for the resource");
6367 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
6368 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6370 return Either.right(responseFormat);
6372 return Either.left(true);
6375 private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
6377 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
6378 if (resourceOperationResponse.isLeft()) {
6379 if (!resourceOperationResponse.left().value()) {
6380 return Either.left(false);
6382 log.debug("resource with name: {}, already exists", resource.getName());
6383 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
6384 return Either.right(errorResponse);
6387 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
6388 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
6389 return Either.right(errorResponse);
6393 * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags();
6395 * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value();
6396 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true);
6400 * 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
6401 * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
6402 * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else {
6403 * 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");
6404 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize,
6405 * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); }
6407 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); }
6410 private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
6412 List<CategoryDefinition> categories = resource.getCategories();
6413 if (categories == null || categories.size() == 0) {
6414 log.debug("Resource category is empty");
6415 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6416 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6417 return Either.right(responseFormat);
6419 if (categories.size() > 1) {
6420 log.debug("Must be only one category for resource");
6421 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
6422 return Either.right(responseFormat);
6424 CategoryDefinition category = categories.get(0);
6425 List<SubCategoryDefinition> subcategories = category.getSubcategories();
6426 if (subcategories == null || subcategories.size() == 0) {
6427 log.debug("Missinig subcategory for resource");
6428 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
6429 return Either.right(responseFormat);
6431 if (subcategories.size() > 1) {
6432 log.debug("Must be only one sub category for resource");
6433 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
6434 return Either.right(responseFormat);
6437 SubCategoryDefinition subcategory = subcategories.get(0);
6439 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
6440 log.debug("Resource category is empty");
6441 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6442 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6443 return Either.right(responseFormat);
6445 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
6446 log.debug("Resource category is empty");
6447 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6448 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6449 return Either.right(responseFormat);
6452 Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
6453 if (validateCategory.isRight()) {
6454 ResponseFormat responseFormat = validateCategory.right().value();
6455 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6456 return Either.right(responseFormat);
6459 return Either.left(true);
6462 private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) {
6463 if (category != null && subcategory != null) {
6464 log.debug("validating resource category {} against valid categories list", category);
6465 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
6466 if (categories.isRight()) {
6467 log.debug("failed to retrive resource categories from Titan");
6468 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
6469 return Either.right(responseFormat);
6471 List<CategoryDefinition> categoryList = categories.left().value();
6472 for (CategoryDefinition cat : categoryList) {
6473 if (cat.getName().equals(category.getName())) {
6474 for (SubCategoryDefinition subcat : cat.getSubcategories()) {
6475 if (subcat.getName().equals(subcategory.getName())) {
6476 return Either.left(true);
6479 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories());
6480 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6483 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
6484 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6486 return Either.left(false);
6489 public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
6490 String vendorRelease = resource.getVendorRelease();
6492 log.debug("validate vendor relese name");
6493 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
6494 log.info("vendor relese name is missing.");
6495 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
6496 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6497 return Either.right(errorResponse);
6500 Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
6501 if (validateVendorReleaseResponse.isRight()) {
6502 ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
6503 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6505 return validateVendorReleaseResponse;
6508 public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
6509 if (vendorRelease != null) {
6510 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
6511 log.info("vendor release exceds limit.");
6512 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
6513 return Either.right(errorResponse);
6516 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
6517 log.info("vendor release is not valid.");
6518 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
6519 return Either.right(errorResponse);
6521 return Either.left(true);
6523 return Either.left(false);
6527 private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
6528 String vendorName = resource.getVendorName();
6529 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
6530 log.info("vendor name is missing.");
6531 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
6532 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6533 return Either.right(errorResponse);
6536 Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
6537 if (validateVendorNameResponse.isRight()) {
6538 ResponseFormat responseFormat = validateVendorNameResponse.right().value();
6539 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6541 return validateVendorNameResponse;
6545 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
6546 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
6547 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber);
6548 if (validateResourceVendorModelNumber.isRight()) {
6549 ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
6550 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6552 return validateResourceVendorModelNumber;
6557 private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
6558 if (vendorName != null) {
6559 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
6560 log.info("vendor name exceds limit.");
6561 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
6562 return Either.right(errorResponse);
6565 if (!ValidationUtils.validateVendorName(vendorName)) {
6566 log.info("vendor name is not valid.");
6567 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
6568 return Either.right(errorResponse);
6570 return Either.left(true);
6573 return Either.left(false);
6577 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
6578 if (resourceVendorModelNumber.equals("")) {
6579 return Either.left(true);
6581 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
6582 log.info("resource vendor model number exceeds limit.");
6583 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
6584 return Either.right(errorResponse);
6586 // resource vendor model number is currently validated as vendor name
6587 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
6588 log.info("resource vendor model number is not valid.");
6589 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
6590 return Either.right(errorResponse);
6592 return Either.left(true);
6598 * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
6599 * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
6600 * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6602 * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
6604 * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
6605 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
6607 * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
6608 * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
6610 * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
6611 * Either.left(false); }
6615 * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
6617 * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
6618 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6620 * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
6621 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
6623 * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
6624 * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6630 * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
6632 * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
6633 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6635 * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
6636 * null); } return validateIcon;
6640 * 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.
6641 * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
6642 * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6647 private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
6648 String cost = resource.getCost();
6651 if (!ValidationUtils.validateCost(cost)) {
6652 log.debug("resource cost is invalid.");
6653 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6654 return Either.right(errorResponse);
6657 return Either.left(true);
6660 private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
6661 log.debug("validate licenseType");
6662 String licenseType = resource.getLicenseType();
6663 if (licenseType != null) {
6664 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
6665 if (!licenseTypes.contains(licenseType)) {
6666 log.debug("License type {} isn't configured");
6667 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6668 if (actionEnum != null) {
6669 // In update case, no audit is required
6670 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6672 return Either.right(responseFormat);
6675 return Either.left(true);
6678 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
6679 Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
6680 if (updatedResource.getDerivedFrom() != null) {
6681 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
6682 log.debug("1. Removing interface artifacts from graph");
6683 // Remove all interface artifacts of resource
6684 String resourceId = updatedResource.getUniqueId();
6685 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
6687 if (interfaces != null) {
6688 Collection<InterfaceDefinition> values = interfaces.values();
6689 for (InterfaceDefinition interfaceDefinition : values) {
6690 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
6692 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
6693 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
6694 if (operations != null) {
6695 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
6696 Operation operation = operationEntry.getValue();
6697 ArtifactDefinition implementation = operation.getImplementationArtifact();
6698 if (implementation != null) {
6699 String uniqueId = implementation.getUniqueId();
6700 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
6701 // only thing that transacts and locks here
6702 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true);
6703 if (deleteArtifactByInterface.isRight()) {
6704 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
6705 if (!inTransaction) {
6706 titanDao.rollback();
6708 return Either.right(deleteArtifactByInterface.right().value());
6711 log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
6715 log.trace("No operations found for interface type {}", interfaceType);
6719 log.debug("2. Removing properties");
6720 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
6722 if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
6723 log.debug("Failed to remove all properties of resource");
6725 titanDao.rollback();
6726 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
6730 log.debug("Derived from wasn't changed during update");
6735 return Either.left(true);
6739 /**** Auditing *******************/
6741 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
6742 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
6744 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
6746 return webApplicationContext.getBean(class1);
6749 public ICapabilityTypeOperation getCapabilityTypeOperation() {
6750 return capabilityTypeOperation;
6753 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
6754 this.capabilityTypeOperation = capabilityTypeOperation;
6757 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
6758 log.debug("validate resource properties default values");
6759 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
6760 List<PropertyDefinition> properties = resource.getProperties();
6762 String innerType = null;
6763 if (properties != null) {
6764 for (PropertyDefinition property : properties) {
6765 if (!propertyOperation.isPropertyTypeValid(property)) {
6766 log.info("Invalid type for property");
6767 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
6768 eitherResult = Either.right(responseFormat);
6772 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
6773 if (allDataTypes.isRight()) {
6774 return Either.right(allDataTypes.right().value());
6777 type = property.getType();
6778 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6779 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value());
6780 innerType = propertyInnerTypeValid.getLeft();
6781 if (!propertyInnerTypeValid.getRight().booleanValue()) {
6782 log.info("Invalid inner type for property");
6783 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
6784 eitherResult = Either.right(responseFormat);
6789 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
6790 log.info("Invalid default value for property");
6791 ResponseFormat responseFormat;
6792 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6793 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
6795 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
6797 eitherResult = Either.right(responseFormat);
6803 return eitherResult;
6807 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
6808 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
6812 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
6813 return vfComponentInstanceBusinessLogic;
6816 private String getComponentTypeForResponse(Component component) {
6817 String componentTypeForResponse = "SERVICE";
6818 if (component instanceof Resource) {
6819 componentTypeForResponse = ((Resource) component).getResourceType().name();
6821 return componentTypeForResponse;
6824 private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6826 Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
6827 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
6829 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
6830 if (eitherNodesTemlates.isLeft()) {
6831 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
6833 if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
6834 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
6835 while (nodesNameValue.hasNext()) {
6836 Entry<String, Object> groupNameValue = nodesNameValue.next();
6838 String groupName = groupNameValue.getKey();
6839 Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue());
6840 if (eitherNode.isRight()) {
6841 String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName();
6842 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6843 return Either.right(eitherNode.right().value());
6845 GroupDefinition groupDefinition = eitherNode.left().value();
6846 groups.put(groupName, groupDefinition);
6855 private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6857 Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
6858 if (inputs.isRight()) {
6859 String message = "Failed when creating inputs: for resource:" + resource.getName();
6860 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6861 Map<String, InputDefinition> resultMap = new HashMap<>();
6862 return Either.left(resultMap);
6866 Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
6871 @SuppressWarnings("unchecked")
6872 private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
6874 GroupDefinition groupInfo = new GroupDefinition();
6875 groupInfo.setName(groupName);
6876 Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
6879 if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
6880 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
6881 String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
6882 if (!StringUtils.isEmpty(groupType)) {
6883 groupInfo.setType(groupType);
6885 log.debug("The 'type' member is not found under group {}", groupName);
6886 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
6889 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
6890 groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
6893 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
6894 Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
6895 if (members != null) {
6896 if (members instanceof List) {
6897 Map<String, String> membersLoaded = new HashMap<>();
6898 List<?> membersAsList = (List<?>) members;
6899 for (Object member : membersAsList) {
6900 membersLoaded.put(member.toString(), "");
6902 groupInfo.setMembers(membersLoaded);
6904 log.debug("The 'members' member is not of type list under group {}", groupName);
6905 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6910 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
6911 Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
6913 Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType);
6914 if (regResponse.isRight())
6915 return Either.right(regResponse.right().value());
6916 if (regResponse.left().value().size() > 0) {
6917 groupInfo.convertFromGroupProperties(regResponse.left().value());
6922 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6924 } catch (Exception e) {
6925 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
6926 log.debug("error when creating group, message:{}", e.getMessage(), e);
6927 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
6933 @SuppressWarnings("unchecked")
6934 private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) {
6936 List<GroupProperty> result = new ArrayList<>();
6938 if (properties == null) {
6939 return Either.left(result);
6942 Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
6944 if (groupTypeRes.isRight()) {
6945 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
6948 Map<String, PropertyDefinition> gtProperties = new HashMap<>();
6949 GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
6951 List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
6953 if (propertiesDef != null) {
6954 gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
6957 if (properties != null) {
6959 if (properties instanceof Map) {
6961 Map<String, Object> props = (Map<String, Object>) properties;
6962 for (Entry<String, Object> entry : props.entrySet()) {
6964 String propName = entry.getKey();
6965 Object value = entry.getValue();
6967 PropertyDefinition gtDefinition = gtProperties.get(propName);
6968 if (gtDefinition == null) {
6969 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType));
6972 ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
6974 String convertedValue = null;
6975 if (value != null) {
6976 if (type == null || value instanceof Map || value instanceof List) {
6977 convertedValue = gson.toJson(value);
6979 convertedValue = value.toString();
6983 GroupProperty groupProperty = new GroupProperty();
6984 groupProperty.setValue(convertedValue);
6985 groupProperty.setName(propName);
6987 log.trace("After building group property {}", groupProperty);
6989 result.add(groupProperty);
6996 return Either.left(result);
6999 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
7003 Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false);
7004 if (userValidation.isRight()) {
7005 return Either.right(userValidation.right().value());
7009 // get resource from csar uuid
7010 Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
7011 if (either.isRight()) {
7012 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
7013 return Either.right(resp);
7016 return Either.left(either.left().value());
7020 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
7024 private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
7025 ResponseFormat responseFormat;
7026 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
7028 for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
7029 String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
7030 if (!defaultCapabilities.containsKey(capabilityType)) {
7031 responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
7032 return Either.right(responseFormat);
7034 CapabilityDefinition delaultCapability = defaultCapabilities.get(capabilityType).get(0);
7035 Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(delaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
7036 if (validationRes.isRight()) {
7037 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value());
7038 return Either.right(responseFormat);
7040 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
7041 validCapabilityList.add(delaultCapability);
7042 validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
7045 return Either.left(validCapabilitiesMap);
7048 private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
7049 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
7050 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
7051 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
7052 for (UploadPropInfo property : uploadedProperties) {
7053 String propertyName = property.getName().toLowerCase();
7054 String propertyType = property.getType();
7055 ComponentInstanceProperty validProperty;
7056 if (defaultProperties.containsKey(propertyName)) {
7057 if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
7058 return Either.right(propertyName);
7061 validProperty = new ComponentInstanceProperty();
7062 validProperty.setName(propertyName);
7063 if (property.getValue() != null)
7064 validProperty.setValue(property.getValue().toString());
7065 validProperty.setDescription(property.getDescription());
7066 validProperty.setPassword(property.isPassword());
7067 validProperties.add(validProperty);
7069 defaultCapability.setProperties(validProperties);
7070 return Either.left(true);
7073 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
7074 Resource resource, User user) {
7076 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
7077 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
7078 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
7081 // add all found Csar artifacts to list to upload
7082 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
7083 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
7084 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
7085 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
7086 ArtifactDefinition foundArtifact;
7088 if (!existingArtifactsToHandle.isEmpty()) {
7089 foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
7090 if (foundArtifact != null) {
7091 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
7092 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
7093 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
7094 // if current artifact already exists, but has different content, add him to the list to update
7095 artifactsToUpdate.add(currNewArtifact);
7097 // remove found artifact from the list of existing artifacts to handle, because it was already handled
7098 existingArtifactsToHandle.remove(foundArtifact);
7099 // and remove found artifact from the list to upload, because it should either be updated or be ignored
7100 artifactsToUpload.remove(currNewArtifact);
7102 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
7103 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
7104 currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
7105 AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
7106 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
7107 responseWrapper.setInnerElement(responseFormat);
7113 if (responseWrapper.isEmpty()) {
7114 existingArtifactsToHandle.stream()
7115 // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
7116 .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
7118 if (responseWrapper.isEmpty()) {
7119 if (!artifactsToUpload.isEmpty())
7120 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
7121 if (!artifactsToUpdate.isEmpty())
7122 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
7123 if (!artifactsToDelete.isEmpty())
7124 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
7126 if (!responseWrapper.isEmpty()) {
7127 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
7129 } catch (Exception e) {
7130 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
7131 responseWrapper.setInnerElement(responseFormat);
7132 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
7134 return nodeTypeArtifactsToHandleRes;
7138 private String buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
7140 String actualVfName;
7141 if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){
7142 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
7143 actualType = ResourceTypeEnum.VFC.name();
7145 actualVfName = vfResourceName;
7146 actualType = nodeResourceType;
7148 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
7149 String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
7150 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
7151 String resourceType = findTypes[0];
7152 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
7154 if (actualName.startsWith(Constants.ABSTRACT)) {
7155 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
7157 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
7159 return toscaResourceName.append(actualName.toLowerCase()).toString();
7162 public ICacheMangerOperation getCacheManagerOperation() {
7163 return cacheManagerOperation;
7166 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
7167 this.cacheManagerOperation = cacheManagerOperation;
7170 ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
7172 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
7174 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
7175 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
7177 if (resourceResultEither.isRight()) {
7178 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
7179 log.debug("Failed to found resource with id {} ", resourceId);
7180 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
7183 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
7184 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
7187 Resource resource = resourceResultEither.left().value();
7188 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
7189 return Either.left(dataTransfer);