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 for(NodeTypeInfo cvfc : nodeTypesInfo.values()){
921 vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
923 return vfcToscaNames;
926 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
927 Map<String, Object> nodes = new HashMap<>();
928 for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){
929 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
931 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
935 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
936 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
937 if (eitherNodeTypes.isLeft()) {
938 nodes.putAll(eitherNodeTypes.left().value());
942 public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
943 log.trace("************* created successfully from YAML, resource TOSCA ");
945 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
946 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
947 csar = csarUIPayload;
949 csar = csarOperation.getCsar(csarUUID, user);
952 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar);
953 if (toscaYamlCsarStatus.isRight()) {
954 return Either.right(toscaYamlCsarStatus.right().value());
956 Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
957 if (toscaYamlChecksum.isRight()) {
958 log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, toscaYamlChecksum.right().value());
959 return Either.right(toscaYamlChecksum.right().value());
961 resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value());
963 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
964 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
965 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
967 CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, false);
968 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
969 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, resource);
970 if (findNodeTypesArtifactsToHandleRes.isRight()) {
971 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
972 return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
974 Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
975 if (createResourceFromYaml.isRight()) {
976 log.debug("Couldn't create resource from YAML");
977 return Either.right(createResourceFromYaml.right().value());
980 Resource vfResource = createResourceFromYaml.left().value();
981 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
982 return Either.left(vfResource);
985 private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) {
986 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
987 List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
988 for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) {
989 extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry);
991 if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
992 setDerivedFrom(nodeTypesInfo, globalSubstitutes);
994 markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo);
995 return nodeTypesInfo;
998 @SuppressWarnings("unchecked")
999 private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo, List<Entry<String, byte[]>> globalSubstitutes) {
1000 for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
1001 String yamlFileContents = new String(entry.getValue());
1002 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1003 Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
1004 if (nodeTypesEither.isLeft()) {
1005 Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
1006 for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
1007 Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
1008 if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
1009 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1010 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
1011 List<String> derivedFrom = new ArrayList<>();
1012 derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
1013 nodeTypeInfo.setDerivedFrom(derivedFrom);
1021 @SuppressWarnings("unchecked")
1022 private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
1023 List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) {
1024 if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
1025 if (!isGlobalSubstitute(entry.getKey())) {
1026 String yamlFileContents = new String(entry.getValue());
1027 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1028 Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
1029 if (substitutionMappingsEither.isLeft()) {
1030 Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value();
1031 if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
1032 NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
1033 nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
1034 nodeTypeInfo.setTemplateFileName(entry.getKey());
1035 nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
1036 nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
1040 globalSubstitutes.add(entry);
1046 @SuppressWarnings("unchecked")
1047 private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
1048 Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
1049 if (nodeTemplatesEither.isLeft()) {
1050 Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
1051 for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
1052 Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
1053 if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
1054 String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
1055 if (nodeTypesInfo.containsKey(type)) {
1056 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
1057 nodeTypeInfo.setNested(true);
1064 private boolean isGlobalSubstitute(String fileName) {
1065 return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
1068 private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
1069 if (csar.isRight()) {
1070 StorageOperationStatus value = csar.right().value();
1071 log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
1072 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1073 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
1074 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1075 return Either.right(responseFormat);
1078 Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils);
1079 if (validateCsarStatus.isRight()) {
1080 ResponseFormat responseFormat = validateCsarStatus.right().value();
1081 log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
1082 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1083 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1084 return Either.right(responseFormat);
1087 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
1089 if (toscaYamlCsarStatus.isRight()) {
1090 ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
1091 log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
1092 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1093 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1094 return Either.right(responseFormat);
1096 return toscaYamlCsarStatus;
1099 private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1100 log.trace("validating resource before create");
1101 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false);
1102 if (eitherCreator.isRight()) {
1103 return Either.right(eitherCreator.right().value());
1105 user.copyData(eitherCreator.left().value());
1107 // validate user role
1108 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
1109 if (validateRes.isRight()) {
1110 return Either.right(validateRes.right().value());
1112 // VF / PNF "derivedFrom" should be null (or ignored)
1113 if (ToscaUtils.isAtomicType(resource)) {
1114 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1115 if (validateDerivedFromNotEmpty.isRight()) {
1116 return Either.right(validateDerivedFromNotEmpty.right().value());
1119 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1122 //resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, nodeTypesArtifactsToCreate, true, false, null
1123 private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1124 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1125 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1126 boolean shouldLock, boolean inTransaction, String nodeName) {
1128 List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
1129 log.trace("************* createResourceFromYaml before parse yaml ");
1130 Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName);
1131 if (parseResourceInfoFromYamlEither.isRight()) {
1132 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
1133 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1134 return Either.right(responseFormat);
1136 log.trace("************* createResourceFromYaml after parse yaml ");
1137 ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
1138 log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
1139 log.trace("************* createResourceFromYaml before create ");
1140 Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1141 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
1142 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1143 log.trace("************* createResourceFromYaml after create ");
1144 if (createdResourceResponse.isRight()) {
1145 ResponseFormat responseFormat = createdResourceResponse.right().value();
1146 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1147 return Either.right(responseFormat);
1150 return createdResourceResponse;
1154 public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
1155 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1156 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1158 Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
1159 if (tosca_version.isRight()) {
1160 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
1161 return Either.right(responseFormat);
1163 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
1164 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
1165 Map<String, Object> mapToConvert = new HashMap<String, Object>();
1166 mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
1167 Resource vfcCreated = null;
1168 if (eitherNodeTypes.isLeft()) {
1169 Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
1170 while (nodesNameValue.hasNext()) {
1171 Entry<String, Object> nodeType = nodesNameValue.next();
1172 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1174 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1175 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1176 Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey());
1177 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1178 if (handleNeatedVfcYaml.isRight()) {
1179 return Either.right(handleNeatedVfcYaml.right().value());
1181 vfcCreated = handleNeatedVfcYaml.left().value();
1182 } else if(csarInfo.getCreatedNodesToscaResourceNames()!= null && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){
1183 log.trace("************* Going to create node {}", nodeType.getKey());
1184 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo);
1185 log.debug("************* Finished to create node {}", nodeType.getKey());
1187 if (resourceCreated.isRight()) {
1188 return Either.right(resourceCreated.right().value());
1190 vfcCreated = resourceCreated.left().value().getLeft();
1191 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName());
1193 if (vfcCreated != null) {
1194 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1196 mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
1202 private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1203 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName) {
1205 Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
1206 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1207 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1209 log.debug("************* Going to create node types from yaml {}", yamlName);
1210 Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(yamlName, resource,
1211 nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1212 if (createNodeTypesRes.isRight()) {
1213 log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, createNodeTypesRes.right().value());
1214 return Either.right(createNodeTypesRes.right().value());
1216 log.debug("************* Finished to create node types from yaml {}", yamlName);
1218 if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1219 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1220 handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1222 return handleNestedVfcRes;
1225 private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts,
1226 Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
1228 Either<Resource, ResponseFormat> result = null;
1229 Resource oldComplexVfc = null;
1230 Resource newComplexVfc = null;
1232 Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1233 if(buildCvfcRes.isRight()){
1234 log.debug("Failed to validate complex VFC for node {}. ", nodeName);
1235 result = buildCvfcRes;
1238 newComplexVfc = buildCvfcRes.left().value();
1239 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade.getLatestByToscaResourceName(newComplexVfc.getToscaResourceName());
1240 if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){
1241 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1242 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1243 } else if(oldComplexVfcRes.isLeft()){
1244 oldComplexVfc = oldComplexVfcRes.left().value();
1248 result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, newComplexVfc);
1250 if(result.isLeft()){
1251 newComplexVfc = result.left().value();
1252 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1253 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1254 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1255 result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
1256 if (result.isRight()) {
1257 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1260 if(result.isLeft()){
1261 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1262 csarInfo.getCvfcToCreateQueue().remove();
1267 private Either<Resource, ResponseFormat> handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo,
1268 CsarInfo csarInfo, String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1270 Either<Resource, ResponseFormat> handleComplexVfcRes;
1271 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1272 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1273 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
1274 markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1275 if(oldComplexVfc == null){
1276 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1277 if (handleComplexVfcRes.isRight()) {
1278 log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName);
1281 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName);
1282 if (handleComplexVfcRes.isRight()) {
1283 log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName);
1286 return handleComplexVfcRes;
1289 private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1291 Either<Resource, ResponseFormat> result = null;
1292 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1293 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1295 if(!csarInfo.getCvfcToCreateQueue().contains(nodeName)){
1296 csarInfo.getCvfcToCreateQueue().add(nodeName);
1298 log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), csarInfo.getVfResourceName());
1299 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, csarInfo.getVfResourceName(), complexVfc.getName()));
1302 result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1303 if(result.isRight()){
1304 log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
1310 private String getNodeTypeActualName(String fullName) {
1311 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1312 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1313 String resourceType = findTypes[0];
1314 return nameWithouNamespacePrefix.substring(resourceType.length());
1317 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
1318 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) {
1320 Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1321 if (resourceMetaData.isRight()) {
1322 return Either.right(resourceMetaData.right().value());
1324 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo.getVfResourceName());
1326 Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1327 if (eitherCreator.isRight()) {
1328 return Either.right(eitherCreator.right().value());
1330 user = eitherCreator.left().value();
1332 return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo);
1335 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, String csarVfName) {
1336 // We need to create a Yaml from each node_types in order to create
1337 // resource from each node type using import normative flow.
1338 DumperOptions options = new DumperOptions();
1339 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1340 Yaml yaml = new Yaml(options);
1342 Map<String, Object> node = new HashMap<>();
1343 node.put(buildNestedToscaResourceName(nodeResourceType, csarVfName, nodeNameValue.getKey()), nodeNameValue.getValue());
1344 mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1346 return yaml.dumpAsMap(mapToConvert);
1349 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1351 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1352 if (validateDerivedFromNotEmpty.isRight()) {
1353 return Either.right(validateDerivedFromNotEmpty.right().value());
1355 return Either.left(true);
1358 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1359 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) {
1361 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1362 Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
1363 return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo);
1366 private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
1367 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1369 // validate nodetype name prefix
1370 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1371 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1372 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1373 return Either.right(responseFormat);
1376 String actualName = this.getNodeTypeActualName(nodeName);
1377 String namePrefix = nodeName.replace(actualName, "");
1378 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1380 // if we import from csar, the node_type name can be
1381 // org.openecomp.resource.abstract.node_name - in this case we always
1383 if (resourceType.equals(Constants.ABSTRACT)) {
1384 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1387 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1388 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1389 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1390 return Either.right(responseFormat);
1394 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1396 // Setting type from name
1397 String type = resourceType.toUpperCase();
1398 resourceMetaData.setResourceType(type);
1400 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1401 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1402 resourceMetaData.setContactId(user.getUserId());
1403 resourceMetaData.setVendorName(resourceVf.getVendorName());
1404 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1407 List<String> tags = new ArrayList<>();
1408 tags.add(resourceMetaData.getName());
1409 resourceMetaData.setTags(tags);
1412 CategoryDefinition category = new CategoryDefinition();
1413 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1414 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1415 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1416 category.addSubCategory(subCategory);
1417 List<CategoryDefinition> categories = new ArrayList<>();
1418 categories.add(category);
1419 resourceMetaData.setCategories(categories);
1421 return Either.left(resourceMetaData);
1424 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1425 Resource cvfc = new Resource();
1426 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1427 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1428 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1429 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1430 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1431 cvfc.setAbstract(true);
1432 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1433 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1434 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1435 cvfc.setContactId(csarInfo.getModifier().getUserId());
1436 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1437 cvfc.setVendorName(resourceVf.getVendorName());
1438 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1439 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1440 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName));
1441 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1443 List<String> tags = new ArrayList<>();
1444 tags.add(cvfc.getName());
1447 CategoryDefinition category = new CategoryDefinition();
1448 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1449 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1450 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1451 category.addSubCategory(subCategory);
1452 List<CategoryDefinition> categories = new ArrayList<>();
1453 categories.add(category);
1454 cvfc.setCategories(categories);
1456 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1457 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1458 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1463 private String buildCvfcName(String resourceVfName, String nodeName) {
1464 String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1465 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1466 String resourceType = findTypes[0];
1467 String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
1468 return addCvfcSuffixToResourceName(resourceName);
1471 private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1472 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo,
1473 CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1474 boolean shouldLock, boolean inTransaction, String nodeName) {
1476 boolean result = true;
1477 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1480 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
1481 if (lockResult.isRight()) {
1482 ResponseFormat responseFormat = lockResult.right().value();
1483 return Either.right(responseFormat);
1485 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1488 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1489 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
1490 if (genericResourceEither.isRight()) {
1492 return genericResourceEither;
1494 Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, csarInfo.getModifier(), isNormative, inTransaction);
1495 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1496 if (createResourcesEither.isRight()) {
1498 return createResourcesEither;
1500 resource = createResourcesEither.left().value();
1501 // add groups to resource
1502 log.trace("************* Going to add inputs from yaml {}", yamlName);
1503 if (resource.shouldGenerateInputs())
1504 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
1506 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1507 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, csarInfo.getModifier(), inputs, inTransaction);
1508 if (createInputsOnResource.isRight()) {
1510 return createInputsOnResource;
1512 resource = createInputsOnResource.left().value();
1513 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1515 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
1516 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1518 createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml,
1519 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
1520 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1521 if (createResourcesEither.isRight()) {
1523 return createResourcesEither;
1526 resource = createResourcesEither.left().value();
1527 // validate update vf module group names
1528 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1529 if (validateUpdateVfGroupNamesRes.isRight()) {
1531 return Either.right(validateUpdateVfGroupNamesRes.right().value());
1533 // add groups to resource
1534 Map<String, GroupDefinition> groups;
1535 log.trace("************* Going to add groups from yaml {}", yamlName);
1537 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1538 groups = validateUpdateVfGroupNamesRes.left().value();
1540 groups = parsedToscaYamlInfo.getGroups();
1542 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, csarInfo.getModifier(), groups);
1543 if (createGroupsOnResource.isRight()) {
1545 return createGroupsOnResource;
1547 resource = createGroupsOnResource.left().value();
1548 log.trace("************* Finished to add groups from yaml {}", yamlName);
1550 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1552 if(resource.getResourceType() == ResourceTypeEnum.CVFC){
1553 if(nodeTypesArtifactsToCreate.containsKey(nodeName) && nodeTypesArtifactsToCreate.get(nodeName) !=null && !nodeTypesArtifactsToCreate.get(nodeName).isEmpty()){
1554 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
1555 handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeName), nodeTypesNewCreatedArtifacts, csarInfo.getModifier(), true, false);
1556 if(handleNodeTypeArtifactsRes.isRight()){
1557 return Either.right(handleNodeTypeArtifactsRes.right().value());
1561 Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, csarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
1563 log.trace("************* Finished to add artifacts from yaml {}", yamlName);
1564 if (createdCsarArtifactsEither.isRight()) {
1566 return createdCsarArtifactsEither;
1568 resource = createdCsarArtifactsEither.left().value();
1570 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1571 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", actionEnum, null);
1572 ASDCKpiApi.countCreatedResourcesKPI();
1573 return Either.left(resource);
1576 if (!inTransaction) {
1578 log.warn("operation failed. do rollback");
1579 titanDao.rollback();
1580 if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
1581 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1582 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
1583 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
1584 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
1585 return Either.right(componentsUtils.getResponseFormat(actionStatus, resource.getName()));
1587 log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
1591 log.debug("operation success. do commit");
1596 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
1601 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1602 if (groups != null && !groups.isEmpty()) {
1603 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1605 if (mergeGroupsUsingResource.isRight()) {
1606 log.debug("Failed to prepare groups for creation");
1607 return Either.right(mergeGroupsUsingResource.right().value());
1609 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1610 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList);
1611 if (createGroups.isRight()) {
1612 return Either.right(createGroups.right().value());
1615 return Either.left(resource);
1617 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1618 if (updatedResource.isRight()) {
1619 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1620 return Either.right(responseFormat);
1622 return Either.left(updatedResource.left().value());
1625 private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1626 if (groups != null && false == groups.isEmpty()) {
1627 List<GroupDefinition> groupsFromResource = resource.getGroups();
1628 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1630 if (mergeGroupsUsingResource.isRight()) {
1631 log.debug("Failed to prepare groups for creation");
1632 return Either.right(mergeGroupsUsingResource.right().value());
1634 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1635 List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
1636 List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
1637 List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
1638 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1639 for (GroupDefinition group : groupsAsList) {
1640 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1641 if (op.isPresent()) {
1642 GroupDefinition groupToUpdate = op.get();
1643 groupToUpdate.setMembers(group.getMembers());
1644 groupsToUpdate.add(groupToUpdate);
1646 groupsToCreate.add(group);
1649 for (GroupDefinition group : groupsFromResource) {
1650 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1651 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1653 groupsToDelete.add(group);
1658 groupsToCreate.addAll(groupsAsList);
1659 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
1660 if (!groupsToCreate.isEmpty()) {
1662 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1663 prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1665 prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1668 if (prepareGroups.isRight()) {
1669 return Either.right(prepareGroups.right().value());
1673 if (!groupsToDelete.isEmpty()) {
1674 prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
1675 if (prepareGroups.isRight()) {
1676 return Either.right(prepareGroups.right().value());
1680 if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
1681 prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
1682 if (prepareGroups.isRight()) {
1683 return Either.right(prepareGroups.right().value());
1688 return Either.left(resource);
1691 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1692 if (updatedResource.isRight()) {
1693 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1694 return Either.right(responseFormat);
1696 return Either.left(updatedResource.left().value());
1699 private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
1700 List<InputDefinition> resourceProperties = resource.getInputs();
1701 if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) {
1703 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
1704 if (createInputs.isRight()) {
1705 return Either.right(createInputs.right().value());
1708 return Either.left(resource);
1711 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1712 if (updatedResource.isRight()) {
1713 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1714 return Either.right(responseFormat);
1716 return Either.left(updatedResource.left().value());
1719 private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1721 List<GroupDefinition> result = new ArrayList<>();
1723 List<ComponentInstance> componentInstances = component.getComponentInstances();
1725 if (groups != null) {
1726 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1727 if (validateCyclicGroupsDependencies.isRight()) {
1728 return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
1730 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1731 String groupName = entry.getKey();
1733 GroupDefinition groupDefinition = entry.getValue();
1735 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1736 updatedGroupDefinition.setMembers(null);
1738 // get the members of the group
1739 Map<String, String> members = groupDefinition.getMembers();
1740 if (members != null) {
1741 Set<String> compInstancesNames = members.keySet();
1743 if (componentInstances == null || true == componentInstances.isEmpty()) {
1744 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1745 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName());
1746 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1748 // Find all component instances with the member names
1749 Map<String, String> memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1750 memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
1751 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
1753 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1755 List<String> foundMembers = new ArrayList<>();
1756 if (relevantInstances != null) {
1757 foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
1759 compInstancesNames.removeAll(foundMembers);
1760 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1761 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1762 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1765 updatedGroupDefinition.setMembers(relevantInstances);
1768 result.add(updatedGroupDefinition);
1771 return Either.left(result);
1775 * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
1780 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1782 Either<Boolean, ResponseFormat> result = Either.left(true);
1784 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1785 while (allGroupsItr.hasNext() && result.isLeft()) {
1786 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1787 // Fetches a group member A
1788 String groupAName = groupAEntry.getKey();
1789 // Finds all group members in group A
1790 Set<String> allGroupAMembersNames = new HashSet<>();
1791 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1792 // If A is a group member of itself found cyclic dependency
1793 if (allGroupAMembersNames.contains(groupAName)) {
1794 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1795 result = Either.right(responseFormat);
1798 } catch (Exception e) {
1799 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1800 result = Either.right(responseFormat);
1801 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1807 * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
1811 * @param allGroupMembers
1814 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1816 // Found Cyclic dependency
1817 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1820 GroupDefinition groupDefinition = allGroups.get(groupName);
1821 // All Members Of Current Group Resource Instances & Other Groups
1822 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1823 // Filtered Members Of Current Group containing only members which
1825 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1826 // Keep Only Elements of type group and not Resource Instances
1827 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1828 // Add Filtered Elements to main Set
1829 peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
1831 collect(Collectors.toList());
1833 // Recursively call the method for all the filtered group members
1834 for (String innerGroupName : currGroupFilteredMembers) {
1835 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1840 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1842 boolean stop = false;
1843 // In Case Not Group Stop
1844 if (!allGroups.containsKey(groupName)) {
1847 // In Case Group Has no members stop
1849 GroupDefinition groupDefinition = allGroups.get(groupName);
1850 stop = MapUtils.isEmpty(groupDefinition.getMembers());
1853 // In Case all group members already contained stop
1855 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1856 Set<String> membersOfTypeGroup = allMembers.stream().
1857 // Filter In Only Group members
1858 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1860 collect(Collectors.toSet());
1861 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1866 private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
1867 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1868 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1871 Either<Resource, ResponseFormat> result;
1872 Either<Resource, ResponseFormat> createResourcesInstancesEither;
1874 log.debug("************* Going to create all nodes {}", yamlName);
1875 Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
1876 if (createdResourcesFromdNodeTypeMap.isRight()) {
1877 log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
1878 return Either.right(createdResourcesFromdNodeTypeMap.right().value());
1880 log.debug("************* Finished to create all nodes {}", yamlName);
1882 log.debug("************* Going to create all resource instances {}", yamlName);
1883 createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes());
1885 if (createResourcesInstancesEither.isRight()) {
1886 log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
1887 result = createResourcesInstancesEither;
1888 return createResourcesInstancesEither;
1890 log.debug("************* Finished to create all resource instances for {}", yamlName);
1891 resource = createResourcesInstancesEither.left().value();
1892 log.debug("************* Going to create all relations {}", yamlName);
1893 createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1895 if (createResourcesInstancesEither.isRight()) {
1896 log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
1897 result = createResourcesInstancesEither;
1900 resource = createResourcesInstancesEither.left().value();
1902 log.debug("************* Finished to create all relations {}", yamlName);
1904 log.debug("************* Going to create positions {}", yamlName);
1905 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1906 log.debug("************* Finished to set positions {}", yamlName);
1907 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
1912 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
1913 List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
1914 artifactsToAdd.stream().forEach(a -> {
1915 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1916 vfcArtifacts.add(a);
1918 log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1924 @SuppressWarnings("unchecked")
1925 private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1926 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1927 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, String nodeName) {
1929 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
1930 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1931 if (nodeTypeEntry.getValue().isNested()) {
1933 Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle,
1934 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1935 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1936 if (createResourceFromYaml.isRight()) {
1937 return Either.right(createResourceFromYaml.right().value());
1942 Map<String, Object> mappedToscaTemplate = null;
1943 if(StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)){
1944 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1946 if(MapUtils.isEmpty(mappedToscaTemplate)){
1947 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1950 Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1951 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1952 if (createdNodeTypeFromMainTemplateEither.isRight()) {
1953 ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
1954 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1955 return Either.right(responseFormat);
1958 // add the created node types to the cache although they are not in the
1960 csarInfo.getCreatedNodes().values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1965 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1966 boolean inTransaction) {
1968 if (csarInfo.getCsar() != null) {
1969 String vendorLicenseModelId = null;
1970 String vfLicenseModelId = null;
1972 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
1973 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1974 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1975 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1976 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
1977 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1978 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
1979 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1984 // Specific Behavior for license artifacts
1985 createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1986 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1987 createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1988 Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1990 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
1991 if (eitherCreateResult.isRight()) {
1992 return Either.right(eitherCreateResult.right().value());
1994 resource = eitherCreateResult.left().value();
1996 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1997 if (artifacsMetaCsarStatus.isLeft()) {
1999 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
2000 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
2001 Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
2002 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
2003 createArtifactsFromCsar = createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2005 createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2006 if (createArtifactsFromCsar.isRight()) {
2007 log.debug("Couldn't create artifacts from artifacts.meta");
2008 return Either.right(createArtifactsFromCsar.right().value());
2011 resource = createArtifactsFromCsar.left().value();
2013 List<GroupDefinition> groupsToDelete = resource.getGroups();
2015 if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
2016 Set<String> artifactsToDelete = new HashSet<String>();
2018 * for (GroupDefinition group : groupsToDelete) { List<String> artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either<GroupDefinition, StorageOperationStatus> deleteGroupEither =
2019 * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus =
2020 * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return
2021 * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
2023 for (String artifactId : artifactsToDelete) {
2024 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
2025 resource, null, null, shouldLock, inTransaction);
2026 if (handleDelete.isRight()) {
2027 log.debug("Couldn't delete artifact {}", artifactId);
2028 return Either.right(handleDelete.right().value());
2031 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2032 if (eitherGetResource.isRight()) {
2033 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2035 return Either.right(responseFormat);
2038 resource = eitherGetResource.left().value();
2042 return Either.left(resource);
2045 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath, String artifactFileName, String artifactType,
2046 ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
2047 boolean inTransaction) {
2048 byte[] artifactFileBytes = null;
2050 if (csarInfo.getCsar().containsKey(artifactPath)) {
2051 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
2053 Either<Boolean, ResponseFormat> result = Either.left(true);
2054 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
2055 if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
2056 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
2057 null, shouldLock, inTransaction);
2058 if (handleDelete.isRight()) {
2059 result = Either.right(handleDelete.right().value());
2064 if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
2065 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
2069 if (artifactFileBytes != null) {
2070 Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
2071 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction);
2072 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2073 if (eitherNonMetaArtifacts.isRight()) {
2074 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
2075 return Either.right(eitherNonMetaArtifacts.right().value());
2081 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2082 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
2083 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
2084 if (eitherResult.isLeft()) {
2085 createdArtifacts.add(eitherResult.left().value());
2090 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) {
2092 String jsonStr = gson.toJson(json);
2094 String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr);
2095 ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
2096 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
2097 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId,
2098 artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true, false);
2099 if (uploadArtifactToService.isRight())
2100 return Either.right(uploadArtifactToService.right().value());
2102 return Either.left(uploadArtifactToService.left().value());
2105 public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
2106 boolean shouldLock, boolean inTransaction) {
2108 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
2109 if (parseResourceInfoFromYamlEither.isRight()) {
2110 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2111 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2112 return Either.right(responseFormat);
2115 List<GroupDefinition> groups = resource.getGroups();
2116 Map<String, ArtifactDefinition> deplymentArtifact = resource.getDeploymentArtifacts();
2117 List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = new ArrayList<ArtifactDefinition>();
2118 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2119 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2120 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2123 int labelCounter = createdDeplymentArtifactsAfterDelete.size();
2125 if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
2126 if (groups != null && !groups.isEmpty()) {
2127 for (GroupDefinition group : groups) {
2128 if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) {
2129 log.debug("failed to update artifacts from csar. List of emty but group not empty");
2130 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2131 return Either.right(responseFormat);
2135 return createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
2138 // find master in group
2139 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
2141 ////////////////////////////////////// create set parsed
2142 ////////////////////////////////////// artifacts///////////////////////////////////////////
2143 Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
2144 Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
2145 Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>();
2147 for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
2148 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2149 parsedGroupTemplate.setGroupName("");
2150 Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<ArtifactTemplateInfo>();
2151 parsedArtifactsNames.add(parsedGroupTemplate);
2152 List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
2153 if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
2154 createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
2156 parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
2160 ///////////////////////////////// find artifacts to
2161 ///////////////////////////////// delete////////////////////////////////////////////////////
2163 Set<ArtifactDefinition> artifactsToDelete = new HashSet<ArtifactDefinition>();
2164 Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<String, List<ArtifactDefinition>>();
2166 Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
2167 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
2169 // Set<String> deletedArtifactsName = new HashSet<String>();
2170 Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete);
2171 if (deletedArtifactsEither.isRight()) {
2172 log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
2174 return Either.right(deletedArtifactsEither.right().value());
2177 List<ArtifactDefinition> deletedArtifacts = deletedArtifactsEither.left().value();
2179 // need to update resource if we updated artifacts
2180 if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) {
2181 for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
2182 ArtifactDefinition artToRemove = null;
2183 for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
2184 if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
2185 artToRemove = artFromResource;
2189 if (artToRemove != null)
2190 createdDeplymentArtifactsAfterDelete.remove(artToRemove);
2195 ////////////// dissociate, associate or create
2196 ////////////// artifacts////////////////////////////
2197 Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
2198 mergedgroup, deletedArtifacts);
2200 if (assDissotiateEither.isRight()) {
2201 log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
2203 return Either.right(assDissotiateEither.right().value());
2206 resource = assDissotiateEither.left().value();
2207 deplymentArtifact = resource.getDeploymentArtifacts();
2208 createdDeplymentArtifactsAfterDelete.clear();
2209 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2210 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2211 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2215 groups = resource.getGroups();
2217 // update vfModule names
2218 Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
2219 if (groups != null && !groups.isEmpty()) {
2220 Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
2221 if (validateUpdateVfGroupNamesRes.isRight()) {
2222 return Either.right(validateUpdateVfGroupNamesRes.right().value());
2224 List<GroupDefinition> heatGroups = null;
2226 heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2229 for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
2231 if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
2232 updatedGroupDef.getMembers().clear();
2234 Map<String, String> members = new HashMap<String, String>();
2235 Set<String> artifactsGroup = new HashSet<String>();
2236 artifactsGroup.addAll(updatedGroupDef.getArtifacts());
2237 associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
2238 if (!members.isEmpty()) {
2239 updatedGroupDef.setMembers(members);
2249 //////////////// create new artifacts in update
2250 //////////////// flow////////////////////////////
2251 List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<ArtifactTemplateInfo>();
2253 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2254 ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
2255 boolean isNewGroup = true;
2256 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2257 Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
2258 Set<ArtifactDefinition> group = groupArtifacts.keySet();
2259 for (ArtifactDefinition artifactInfo : group) {
2260 if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
2261 parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
2267 newArtifactsGroup.add(parsedArtifactMaster);
2270 if (!newArtifactsGroup.isEmpty()) {
2271 Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
2272 int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
2273 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter);
2274 if (validateGroupNamesRes.isRight()) {
2275 return Either.right(validateGroupNamesRes.right().value());
2277 Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
2278 if (resStatus.isRight())
2283 if (!groupForAssociateWithMembers.isEmpty()) {
2285 List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
2287 Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId);
2288 if (updateVersionEither.isRight()) {
2289 log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
2291 return Either.right(updateVersionEither.right().value());
2296 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2297 if (eitherGerResource.isRight()) {
2298 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2300 return Either.right(responseFormat);
2303 return Either.left(eitherGerResource.left().value());
2307 private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
2308 Map<String, List<ArtifactDefinition>> groupToDelete) {
2309 List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
2310 String resourceId = resource.getUniqueId();
2311 if (!artifactsToDelete.isEmpty()) {
2312 for (ArtifactDefinition artifact : artifactsToDelete) {
2313 String artifactType = artifact.getArtifactType();
2314 ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
2315 if (artifactTypeEnum == ArtifactTypeEnum.HEAT_ENV) {
2318 * Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if
2319 * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact {} . status is {}", artifact.getUniqueId(), status); ActionStatus
2320 * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); }
2322 * deletedArtifacts.add(removeArifactFromGraph.left().value());
2326 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
2327 null, null, shouldLock, inTransaction);
2328 if (handleDelete.isRight()) {
2329 return Either.right(handleDelete.right().value());
2332 deletedArtifacts.add(handleDelete.left().value().left().value());
2337 if (!groupToDelete.isEmpty()) {
2338 log.debug("try to delete group");
2339 List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
2340 List<GroupDefinition> groups = resource.getGroups();
2341 for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
2342 Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
2343 if (op.isPresent()) {
2344 groupDefinitionstoDelete.add(op.get());
2348 if (!groupDefinitionstoDelete.isEmpty()) {
2349 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete);
2350 if (prepareGroups.isRight()) {
2351 return Either.right(prepareGroups.right().value());
2355 return Either.left(deletedArtifacts);
2358 private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
2359 boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
2360 Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
2361 Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
2362 Either<Resource, ResponseFormat> resEither = Either.left(resource);
2363 for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
2364 List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts);
2365 GroupDefinition grDef = entry.getKey();
2366 if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
2367 for (ArtifactDefinition art : dissArtifactsInGroup) {
2368 grDef.getArtifacts().remove(art.getUniqueId());
2369 grDef.getArtifactsUuid().remove(art.getArtifactUUID());
2373 List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
2374 if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
2375 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
2377 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
2378 if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
2379 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
2382 if (!artifactsToUpdateMap.isEmpty()) {
2383 List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>();
2384 for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
2385 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
2386 GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
2388 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
2389 String prevUUID = artifact.getKey().getArtifactUUID();
2390 String prevId = artifact.getKey().getUniqueId();
2391 Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
2392 artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
2393 if (updateArtifactEither.isRight()) {
2394 log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
2395 resEither = Either.right(updateArtifactEither.right().value());
2398 ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
2399 if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
2400 groupToUpdate.getArtifacts().remove(prevId);
2401 groupToUpdate.getArtifactsUuid().remove(prevUUID);
2402 groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
2403 groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
2409 for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
2410 List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
2411 Set<String> arifactsUids = new HashSet<String>();
2412 Set<String> arifactsUuids = new HashSet<String>();
2413 for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
2419 boolean isCreate = true;
2420 for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
2421 if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
2422 arifactsUids.add(createdArtifact.getUniqueId());
2423 arifactsUuids.add(createdArtifact.getArtifactUUID());
2425 String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
2426 if (!heatEnvId.isEmpty()) {
2427 arifactsUids.add(heatEnvId);
2428 Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
2429 if (op.isPresent()) {
2430 this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
2439 if (isCreate) { // check if already created
2440 for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
2441 if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
2442 arifactsUids.add(createdNewArtifact.getUniqueId());
2443 arifactsUuids.add(createdNewArtifact.getArtifactUUID());
2445 String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
2446 if (!heatEnvId.isEmpty()) {
2447 arifactsUids.add(heatEnvId);
2455 Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
2456 if (createArtifactEither.isRight()) {
2457 resEither = Either.right(createArtifactEither.right().value());
2460 ArtifactDefinition createdArtifact = createArtifactEither.left().value();
2461 arifactsUids.add(createdArtifact.getUniqueId());
2462 arifactsUuids.add(createdArtifact.getArtifactUUID());
2463 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
2464 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2465 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2466 resource.getName(), csarInfo.getModifier(), resource, null);
2467 if (createHeatEnvPlaceHolder.isRight()) {
2468 return Either.right(createHeatEnvPlaceHolder.right().value());
2470 String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
2471 arifactsUids.add(heatEnvId);
2476 if (arifactsUids.size() > 0) {
2477 List<String> artifactsToAssociate = new ArrayList<String>();
2478 artifactsToAssociate.addAll(arifactsUids);
2479 GroupDefinition assotiateGroup = associateEntry.getKey();
2480 assotiateGroup.getArtifacts().addAll(arifactsUids);
2481 assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
2486 * if (!associateArtifactGroup.isEmpty()) {
2488 * log.debug("Try to associate artifacts to groups.");
2490 * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
2491 * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
2496 ComponentParametersView parametersView = new ComponentParametersView();
2497 parametersView.disableAll();
2498 parametersView.setIgnoreComponentInstances(false);
2499 parametersView.setIgnoreUsers(false);
2500 parametersView.setIgnoreArtifacts(false);
2501 parametersView.setIgnoreGroups(false);
2503 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2505 if (eitherGerResource.isRight()) {
2506 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2508 resEither = Either.right(responseFormat);
2512 resEither = Either.left(eitherGerResource.left().value());
2516 private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
2517 Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
2518 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
2519 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2520 Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
2521 boolean isNeedToDeleteGroup = true;
2522 List<ArtifactDefinition> listToDelete = null;
2523 for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
2524 listToDelete = createdArtifactMap.get(maserArtifact);
2525 for (ArtifactDefinition artToDelete : listToDelete) {
2526 findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
2528 if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
2529 GroupDefinition group = groupListEntry.getKey();
2530 for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
2531 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
2532 group.getArtifacts().remove(artifactDefinition.getUniqueId());
2535 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
2536 group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
2543 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
2544 if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
2545 MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
2546 mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
2547 mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
2548 mergedgroup.put(groupListEntry.getKey(), mergedGroup);
2549 isNeedToDeleteGroup = false;
2555 if (isNeedToDeleteGroup) {
2556 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
2563 private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
2564 List<ArtifactDefinition> createdDeplymentArtifacts) {
2565 boolean isNeedToDeleteArtifact = true;
2566 String artifactType = artifact.getArtifactType();
2567 ArtifactDefinition generatedFromArt = null;
2568 if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
2569 Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
2571 generatedFromArt = op.get();
2575 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2576 Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
2577 for (ArtifactTemplateInfo template : artifactsNames) {
2578 if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
2579 isNeedToDeleteArtifact = false;
2583 if (generatedFromArt != null) {
2584 if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
2585 isNeedToDeleteArtifact = false;
2593 if (isNeedToDeleteArtifact) {
2594 artifactsToDelete.add(artifact);
2599 private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
2600 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>();
2602 for (GroupDefinition group : groups) {
2603 Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>();
2604 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
2605 List<String> artifactsList = group.getArtifacts();
2606 if (artifactsList != null && !artifactsList.isEmpty()) {
2608 ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList);
2609 if (masterArtifact != null)
2610 gupsMap.put(masterArtifact, artifacts);
2611 groupArtifact.put(group, gupsMap);
2615 return groupArtifact;
2618 private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
2620 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2621 parsedArtifactsName.add(parsedGroupTemplate);
2622 List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
2623 if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
2624 createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
2629 public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
2630 boolean shouldLock, boolean inTransaction) {
2632 log.debug("parseResourceArtifactsInfoFromFile start");
2633 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
2634 if (parseResourceInfoFromYamlEither.isRight()) {
2635 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2636 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2637 return Either.right(responseFormat);
2639 log.debug("parseResourceArtifactsInfoFromFile end");
2641 log.debug("createResourceArtifacts start");
2642 Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
2643 if (respStatus.isRight()) {
2646 log.debug("createResourceArtifacts end");
2647 log.debug("getResource start");
2648 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2649 log.debug("getResource end");
2650 if (eitherGerResource.isRight()) {
2651 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2653 return Either.right(responseFormat);
2656 return Either.left(eitherGerResource.left().value());
2660 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
2661 List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
2662 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2663 List<GroupDefinition> createdGroups = resource.getGroups();
2664 List<GroupDefinition> heatGroups = null;
2665 if (createdGroups != null && !createdGroups.isEmpty()) {
2666 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2669 List<GroupDefinition> needToAdd = new ArrayList<>();
2670 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2671 String groupName = groupTemplateInfo.getGroupName();
2672 Set<String> artifactsGroup = new HashSet<String>();
2673 Set<String> artifactsUUIDGroup = new HashSet<String>();
2675 resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
2676 if (resStatus.isRight())
2679 Map<String, String> members = new HashMap<String, String>();
2680 associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
2682 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2683 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2685 GroupDefinition groupDefinition = new GroupDefinition();
2686 groupDefinition.setName(groupName);
2687 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2688 groupDefinition.setArtifacts(artifactsList);
2689 groupDefinition.setArtifactsUuid(artifactsUUIDList);
2691 if (!members.isEmpty())
2692 groupDefinition.setMembers(members);
2694 List<GroupProperty> properties = new ArrayList<GroupProperty>();
2695 GroupProperty prop = new GroupProperty();
2696 prop.setName(Constants.IS_BASE);
2697 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2698 properties.add(prop);
2700 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2701 createdArtifacts.addAll(createdNewArtifacts);
2702 createdArtifacts.addAll(artifactsFromResource);
2703 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2704 if (getLatestGroupTypeRes.isRight()) {
2705 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2707 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2708 groupDefinition.convertFromGroupProperties(properties);
2710 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2711 // if (createGroup.isRight())
2712 // return Either.right(createGroup.right().value());
2713 needToAdd.add(groupDefinition);
2715 ComponentParametersView componentParametersView = new ComponentParametersView();
2716 componentParametersView.disableAll();
2717 componentParametersView.setIgnoreArtifacts(false);
2718 componentParametersView.setIgnoreGroups(false);
2719 componentParametersView.setIgnoreComponentInstances(false);
2721 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2722 if (component.isRight()) {
2723 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2725 resource = component.left().value();
2727 Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd);
2728 if (addGroups.isRight())
2729 return Either.right(addGroups.right().value());
2734 private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
2735 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
2736 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2737 String artifactFileName = artifactTemplateInfo.getFileName();
2738 String artifactUid = "";
2739 String artifactUUID = "";
2740 String artifactEnvUid = "";
2741 boolean alreadyExist = false;
2743 // check if artifacts already exist
2744 if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
2745 for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
2746 if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
2747 artifactUid = artifactFromResource.getUniqueId();
2748 artifactUUID = artifactFromResource.getArtifactUUID();
2749 if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2750 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
2751 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2752 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
2754 alreadyExist = true;
2755 artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
2762 if (!alreadyExist) {
2763 for (ArtifactDefinition createdArtifact : createdArtifacts) {
2764 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
2765 artifactUid = createdArtifact.getUniqueId();
2766 artifactUUID = createdArtifact.getArtifactUUID();
2768 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2769 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
2770 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2771 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
2773 alreadyExist = true;
2774 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
2780 // if not exist need to create
2781 if (!alreadyExist) {
2783 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
2784 if (newArtifactEither.isRight()) {
2785 resStatus = Either.right(newArtifactEither.right().value());
2788 ArtifactDefinition newArtifact = newArtifactEither.left().value();
2789 artifactUid = newArtifact.getUniqueId();
2790 artifactUUID = newArtifact.getArtifactUUID();
2791 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
2792 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2793 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2794 resource.getName(), csarInfo.getModifier(), resource, null);
2795 if (createHeatEnvPlaceHolder.isRight()) {
2796 return Either.right(createHeatEnvPlaceHolder.right().value());
2798 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
2802 artifactsGroup.add(artifactUid);
2803 artifactsUUIDGroup.add(artifactUUID);
2804 if (!artifactEnvUid.isEmpty()) {
2805 artifactsGroup.add(artifactEnvUid);
2808 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
2809 if (relatedArtifacts != null) {
2810 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
2811 resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
2812 if (resStatus.isRight())
2819 private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
2820 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
2822 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2824 Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
2826 for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
2827 if (groupTemplateList != null) {
2828 resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
2829 if (resStatus.isRight())
2838 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) {
2840 Either<Resource, ResponseFormat> resStatus = null;
2841 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2844 List<NonMetaArtifactInfo> artifactPathAndNameList =
2845 // Stream of file paths contained in csar
2846 csarInfo.getCsar().entrySet().stream()
2847 // Filter in only VF artifact path location
2848 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
2849 // Validate and add warnings
2850 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2851 // Filter in Non Warnings
2852 .filter(e -> e.isLeft())
2853 // Convert from Either to NonMetaArtifactInfo
2854 .map(e -> e.left().value())
2856 .collect(Collectors.toList());
2858 Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
2859 if (responseFormatEither.isRight()) {
2860 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
2864 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2866 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
2867 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2868 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
2870 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, csarInfo.getModifier());
2872 if (findVfCsarArtifactsToHandleRes.isRight()) {
2873 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2875 if (resStatus == null) {
2876 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2879 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2880 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
2882 Optional<ResponseFormat> optionalCreateInDBError =
2883 // Stream of artifacts to be created
2884 currArtifactOperationPair.getValue().stream()
2885 // create each artifact
2886 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2887 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
2889 // filter in only error
2890 .filter(e -> e.isRight()).
2891 // Convert the error from either to ResponseFormat
2892 map(e -> e.right().value()).
2893 // Check if an error occurred
2895 // Error found on artifact Creation
2896 if (optionalCreateInDBError.isPresent()) {
2897 resStatus = Either.right(optionalCreateInDBError.get());
2902 if (resStatus == null) {
2903 Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2904 resStatus = toscaElement.bimap(resourceResponse -> resourceResponse,
2905 storageResponse -> componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageResponse), resource));
2907 } catch (Exception e) {
2908 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2909 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2911 CsarUtils.handleWarningMessages(collectedWarningMessages);
2916 private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
2917 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2918 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2919 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2920 return Either.right(nonMetaArtifactInfo.getArtifactName());
2923 return Either.left(true);
2927 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2929 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2930 // collect all Deployment and Informational artifacts of VF
2931 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2932 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2934 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2935 existingArtifacts.addAll(resource.getArtifacts().values());
2937 existingArtifacts = existingArtifacts.stream()
2938 // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
2939 .filter(this::isNonMetaArtifact).collect(Collectors.toList());
2941 List<String> artifactsToIgnore = new ArrayList<>();
2942 // collect IDs of Artifacts of VF which belongs to any group
2943 if (resource.getGroups() != null) {
2944 resource.getGroups().stream().forEach(g -> {
2945 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
2946 artifactsToIgnore.addAll(g.getArtifacts());
2949 existingArtifacts = existingArtifacts.stream()
2950 // filter artifacts which belongs to any group
2951 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
2952 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2955 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2956 boolean result = true;
2957 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2963 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2964 boolean result = true;
2965 if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2971 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
2972 int labelCounter, boolean shouldLock, boolean inTransaction) {
2973 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2974 List<GroupDefinition> createdGroups = resource.getGroups();
2975 List<GroupDefinition> heatGroups = null;
2976 if (createdGroups != null && !createdGroups.isEmpty()) {
2978 // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
2979 // e.getArtifacts().stream()).filter(p ->
2980 // relevantArtifactTypes.contains(p.getArtifactType()
2981 // )).collect(Collectors.toList());
2982 // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
2983 // e -> e.getProperties().stream().filter(p ->
2984 // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
2985 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2988 List<GroupDefinition> needToCreate = new ArrayList<>();
2989 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2990 String groupName = groupTemplateInfo.getGroupName();
2991 Set<String> artifactsGroup = new HashSet<String>();
2992 Set<String> artifactsUUIDGroup = new HashSet<String>();
2994 log.debug("createDeploymentArtifactsFromCsar start");
2995 resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
2996 log.debug("createDeploymentArtifactsFromCsar end");
2997 if (resStatus.isRight())
3000 Map<String, String> members = new HashMap<String, String>();
3001 associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
3003 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
3004 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
3006 GroupDefinition groupDefinition = new GroupDefinition();
3007 groupDefinition.setName(groupName);
3008 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
3009 groupDefinition.setArtifacts(artifactsList);
3010 groupDefinition.setArtifactsUuid(artifactsUUIDList);
3012 if (!members.isEmpty())
3013 groupDefinition.setMembers(members);
3014 List<GroupProperty> properties = new ArrayList<GroupProperty>();
3015 GroupProperty prop = new GroupProperty();
3016 prop.setName(Constants.IS_BASE);
3017 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
3018 properties.add(prop);
3019 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
3020 if (getLatestGroupTypeRes.isRight()) {
3021 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
3023 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
3024 groupDefinition.convertFromGroupProperties(properties);
3025 log.debug("createGroup start");
3027 // Since in these groups we handle only artifacts, then no need to
3028 // fetch component instances
3030 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
3031 // log.debug("createGroup end");
3032 // if (createGroup.isRight())
3033 // return Either.right(createGroup.right().value());
3034 needToCreate.add(groupDefinition);
3037 ComponentParametersView componentParametersView = new ComponentParametersView();
3038 componentParametersView.disableAll();
3039 componentParametersView.setIgnoreUsers(false);
3040 componentParametersView.setIgnoreArtifacts(false);
3041 componentParametersView.setIgnoreGroups(false);
3043 componentParametersView.setIgnoreComponentInstances(false);
3045 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
3046 if (component.isRight()) {
3047 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3050 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate);
3051 if (createGroups.isRight()) {
3052 return Either.right(createGroups.right().value());
3058 public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
3059 Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
3060 vfModuleProperties.entrySet().forEach(p -> {
3061 GroupProperty prop = new GroupProperty();
3062 prop.setName(p.getKey());
3064 prop.setValue(p.getValue().getForBaseModule());
3065 prop.setDefaultValue(p.getValue().getForBaseModule());
3067 prop.setValue(p.getValue().getForNonBaseModule());
3068 prop.setDefaultValue(p.getValue().getForNonBaseModule());
3070 properties.add(prop);
3073 GroupProperty proplabel = new GroupProperty();
3074 proplabel.setName("vf_module_label");
3076 Matcher matcher = pattern.matcher(moduleName);
3078 if (matcher.find()) {
3079 proplabel.setValue(matcher.group(1));
3080 proplabel.setDefaultValue(matcher.group(1));
3082 proplabel.setValue(moduleName);
3083 proplabel.setDefaultValue(moduleName);
3085 properties.add(proplabel);
3087 GroupProperty propvolume = new GroupProperty();
3088 propvolume.setName("volume_group");
3089 boolean isVolume = false;
3090 for (String artifactId : artifactsInGroup) {
3091 ArtifactDefinition artifactDef = null;
3092 artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
3093 if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
3098 propvolume.setValue(String.valueOf(isVolume));
3099 propvolume.setDefaultValue(String.valueOf(isVolume));
3100 properties.add(propvolume);
3101 mergeWithGroupTypeProperties(properties, groupType.getProperties());
3105 private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
3107 Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
3108 for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
3109 if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
3110 properties.add(new GroupProperty(groupTypeProperty));
3115 private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
3116 for (ArtifactDefinition artifact : createdArtifacts) {
3117 if (artifact.getUniqueId().equals(artifactId)) {
3124 private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
3125 if (heatGroups != null && !heatGroups.isEmpty()) {
3126 for (GroupDefinition heatGroup : heatGroups) {
3127 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
3128 if (grpoupProps != null) {
3129 Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
3130 if (op.isPresent()) {
3131 GroupProperty prop = op.get();
3132 String heatFileNAme = prop.getValue();
3133 if (null == heatFileNAme || heatFileNAme.isEmpty())
3135 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
3136 for (String artifactId : artifactsGroup) {
3137 Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3138 if (opArt.isPresent()) {
3139 artifacts.add(opArt.get());
3141 if (artifactsFromResource != null) {
3142 opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3143 if (opArt.isPresent()) {
3144 artifacts.add(opArt.get());
3148 Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
3149 if (resOp.isPresent()) {
3150 members.putAll(heatGroup.getMembers());
3159 private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
3160 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3161 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
3162 String artifactFileName = artifactTemplateInfo.getFileName();
3163 String artifactUid = "";
3164 String artifactEnvUid = "";
3165 String artifactUUID = "";
3166 boolean alreadyExist = false;
3168 // check if artifacts already exist
3169 for (ArtifactDefinition createdArtifact : createdArtifacts) {
3170 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
3171 artifactUid = createdArtifact.getUniqueId();
3172 artifactUUID = createdArtifact.getArtifactUUID();
3173 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3174 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
3175 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3176 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
3178 alreadyExist = true;
3179 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
3183 // if not exist need to create
3184 if (!alreadyExist) {
3186 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3187 if (newArtifactEither.isRight()) {
3188 resStatus = Either.right(newArtifactEither.right().value());
3191 ArtifactDefinition newArtifact = newArtifactEither.left().value();
3192 artifactUid = newArtifact.getUniqueId();
3193 artifactUUID = newArtifact.getArtifactUUID();
3195 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
3196 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3197 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
3198 resource.getName(), csarInfo.getModifier(), resource, null);
3199 if (createHeatEnvPlaceHolder.isRight()) {
3200 return Either.right(createHeatEnvPlaceHolder.right().value());
3202 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
3206 artifactsGroup.add(artifactUid);
3207 artifactsUUIDGroup.add(artifactUUID);
3208 if (!artifactEnvUid.isEmpty()) {
3209 artifactsGroup.add(artifactEnvUid);
3212 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3213 if (relatedArtifacts != null) {
3214 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
3215 resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3216 if (resStatus.isRight())
3223 private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
3224 String artifactEnvUid = "";
3225 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
3226 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3227 artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
3229 return artifactEnvUid;
3232 private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
3233 List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3234 final String artifactFileName = artifactTemplateInfo.getFileName();
3235 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils);
3236 if (artifactContententStatus.isRight()) {
3237 return Either.right(artifactContententStatus.right().value());
3239 labelCounter += createdArtifacts.size();
3241 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3243 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3244 shoudLock, inTransaction);
3246 if (uploadArtifactToService.isRight())
3247 return Either.right(uploadArtifactToService.right().value());
3249 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3250 if (currentInfo.getHeatParameters() != null) {
3252 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, false);
3253 if (updateEnvEither.isRight()) {
3254 log.debug("failed to update parameters to artifact {}", artifactFileName);
3255 return Either.right(updateEnvEither.right().value());
3258 currentInfo = updateEnvEither.left().value();
3262 createdArtifacts.add(currentInfo);
3264 return Either.left(currentInfo);
3268 private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
3269 List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
3271 Either<ArtifactDefinition, ResponseFormat> resStatus = null;
3272 String artifactFileName = artifactTemplateInfo.getFileName();
3274 // check if artifacts already exist
3275 for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
3276 if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
3277 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3278 log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
3279 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3280 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
3283 resStatus = Either.left(updatedArtifact);
3289 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
3290 if (artifactContententStatus.isRight()) {
3291 resStatus = Either.right(artifactContententStatus.right().value());
3295 Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
3296 oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
3298 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
3299 shouldLock, inTransaction);
3301 if (uploadArtifactToService.isRight()) {
3302 resStatus = Either.right(uploadArtifactToService.right().value());
3305 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3307 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, true);
3308 if (updateEnvEither.isRight()) {
3309 log.debug("failed to update parameters to artifact {}", artifactFileName);
3310 resStatus = Either.right(updateEnvEither.right().value());
3313 // TODO evg update env time ( must be separate US for this!!!!)
3315 updatedArtifacts.add(updateEnvEither.left().value());
3316 resStatus = Either.left(updateEnvEither.left().value());
3322 private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
3323 Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
3324 if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
3326 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
3328 if (artifactparamsStatus.isRight()) {
3329 resStatus = Either.right(artifactparamsStatus.right().value());
3332 Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
3334 * if (propsStatus.isRight()) {
3336 * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
3338 if (propsStatus.isLeft()) {
3339 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
3340 List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
3341 // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3343 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3346 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3348 paramName = heatEnvParam.getName();
3349 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3350 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3352 String updatedParamValue = heatEnvParam.getCurrentValue();
3353 if (updatedParamValue == null)
3354 updatedParamValue = heatEnvParam.getDefaultValue();
3355 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3356 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3357 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3358 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3359 resStatus = Either.right(responseFormat);
3362 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3363 // newHeatEnvParams.add(currHeatParam);
3368 currentInfo.setListHeatParameters(currentHeatEnvParams);
3369 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
3370 if (updateArifactOnResource.isRight()) {
3371 log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
3372 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3374 resStatus = Either.left(updateArifactOnResource.left().value());
3379 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3380 Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
3381 if (op.isPresent()) {
3382 ArtifactDefinition artifactInfoHeatEnv = op.get();
3383 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
3384 if (updateArifactOnResource.isRight()) {
3385 log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
3386 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3393 private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
3394 // extract heat parameters
3395 String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
3396 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
3397 if (heatParameters.isRight()) {
3398 log.debug("File {} is not in expected key-value form in csar ", fileName);
3399 BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR);
3400 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
3403 return Either.left(heatParameters.left().value());
3407 private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) {
3409 Map<String, Object> json = new HashMap<String, Object>();
3410 String artifactName = artifactTemplateInfo.getFileName();
3412 json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
3413 json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
3414 json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
3416 // DE250204: There is no need to check if base64 encoding.
3418 // String encodedPayload = new String(artifactContentent);
3419 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3420 // if (!isEncoded) {
3421 String encodedPayload = Base64.encodeBase64String(artifactContentent);
3423 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3424 String displayName = artifactName;
3425 if (artifactName.lastIndexOf(".") > 0)
3426 displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
3427 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3428 String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
3429 json.put(Constants.ARTIFACT_LABEL, label);
3430 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
3431 List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3432 json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
3433 : 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()));
3437 private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
3438 List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3440 Map<String, Object> json = new HashMap<String, Object>();
3441 if (artifactId != null && !artifactId.isEmpty())
3442 json.put(Constants.ARTIFACT_ID, artifactId);
3444 json.put(Constants.ARTIFACT_NAME, artifactName);
3445 json.put(Constants.ARTIFACT_TYPE, artifactType);
3446 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3448 String encodedPayload = new String(artifactContentent);
3450 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3451 // if (!isEncoded) {
3452 log.debug("payload is encoded. perform decode");
3453 encodedPayload = Base64.encodeBase64String(artifactContentent);
3456 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3457 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3458 json.put(Constants.ARTIFACT_LABEL, label);
3459 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3460 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3461 : 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()));
3465 @SuppressWarnings({ "unchecked", "static-access" })
3466 private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
3469 JsonObject jsonElement = new JsonObject();
3470 jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
3472 JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
3473 if (importStructureElement == null || importStructureElement.isJsonNull()) {
3474 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3475 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3476 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3479 Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>();
3480 artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
3481 if (artifactTemplateMap.isEmpty()) {
3482 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3483 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3484 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3487 Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
3488 Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>();
3489 List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
3490 for (String artifactsTypeKey : artifactsTypeKeys) {
3492 List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
3493 Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
3494 if (artifactTemplateInfoListPairStatus.isRight()) {
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(artifactTemplateInfoListPairStatus.right().value());
3499 List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
3500 if (artifactTemplateInfoList == null) {
3501 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3502 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3503 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3506 allGroups.addAll(artifactTemplateInfoList);
3507 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList);
3509 int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
3510 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
3511 if (validateGroupNamesRes.isRight()) {
3512 return Either.right(validateGroupNamesRes.right().value());
3514 return Either.left(artifactsMap);
3515 } catch (Exception e) {
3516 log.debug("Artifact file is not in expected format, fileName {}", artifactFileName);
3517 log.debug("failed with exception.", e);
3518 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3519 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3524 private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) {
3525 List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>();
3526 for (Map<String, Object> o : jsonObject) {
3527 Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
3528 if (artifacttemplateInfoStatus.isRight()) {
3529 return Either.right(artifacttemplateInfoStatus.right().value());
3532 ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
3533 if (artifacttemplateInfo != null) {
3534 artifactTemplateInfoList.add(artifacttemplateInfo);
3538 return Either.left(artifactTemplateInfoList);
3541 private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3542 log.debug("createResourceInstancesRelations try to create relations ");
3543 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3544 if (uploadResInstancesMap == null) {
3545 log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
3546 BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR);
3548 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3549 return Either.right(responseFormat);
3552 if (componentInstancesList == null || componentInstancesList.isEmpty()) {
3553 log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
3554 BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3556 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3557 return Either.right(responseFormat);
3560 log.debug("Before validateAndUpdatePropertyValue");
3561 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
3562 if (allDataTypes.isRight()) {
3563 TitanOperationStatus status = allDataTypes.right().value();
3564 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
3565 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
3569 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
3570 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
3571 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
3572 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
3573 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
3574 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
3575 Map<String, Resource> originCompMap = new HashMap<>();
3576 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
3578 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
3580 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3581 log.trace("Processing entry: {}", entry);
3582 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3583 ComponentInstance currentCompInstance = null;
3584 for (ComponentInstance compInstance : componentInstancesList) {
3585 log.trace("Processing component instance: {}", compInstance);
3586 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3587 currentCompInstance = compInstance;
3592 if (currentCompInstance == null) {
3593 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3594 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3595 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3596 return Either.right(responseFormat);
3598 String resourceInstanceId = currentCompInstance.getUniqueId();
3599 Resource originResource;
3600 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
3601 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
3602 if (getOriginResourceRes.isRight()) {
3603 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), getOriginResourceRes);
3604 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
3605 return Either.right(responseFormat);
3607 originResource = getOriginResourceRes.left().value();
3608 originCompMap.put(originResource.getUniqueId(), originResource);
3610 originResource = originCompMap.get(currentCompInstance.getComponentUid());
3612 if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
3613 instCapabilties.put(currentCompInstance, originResource.getCapabilities());
3614 if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
3615 instRequirements.put(currentCompInstance, originResource.getRequirements());
3616 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
3617 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
3618 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
3619 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
3620 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
3621 instAttributes.put(resourceInstanceId, originResource.getAttributes());
3622 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
3623 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
3624 if (addPropertiesValueToRiRes.getStatus() != 200) {
3625 return Either.right(addPropertiesValueToRiRes);
3628 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(originResource);
3629 if (genericResourceEither.isRight()) {
3630 return genericResourceEither;
3632 log.trace("************* Going to add inputs from from original resource {} to resource instance. ", originResource.getName());
3633 if (originResource.shouldGenerateInputs())
3634 generateInputsFromGenericTypeProperties(originResource, genericResourceEither.left().value());
3636 ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
3637 if (addInputValueToRiRes.getStatus() != 200) {
3638 return Either.right(addInputValueToRiRes);
3643 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
3644 if (addPropToInst.isRight()) {
3645 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
3646 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
3647 return Either.right(responseFormat);
3649 if (instInputs != null && !instInputs.isEmpty()) {
3650 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
3651 if (addInputToInst.isRight()) {
3652 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
3653 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
3654 return Either.right(responseFormat);
3657 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
3658 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3659 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3660 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3661 return Either.right(responseFormat);
3664 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user);
3665 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3666 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3667 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3668 return Either.right(responseFormat);
3671 addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
3672 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3673 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3674 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3675 return Either.right(responseFormat);
3678 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
3679 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3680 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3681 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3682 return Either.right(responseFormat);
3685 ComponentParametersView parametersView = new ComponentParametersView();
3686 parametersView.disableAll();
3687 parametersView.setIgnoreComponentInstances(false);
3688 parametersView.setIgnoreComponentInstancesProperties(false);
3689 parametersView.setIgnoreCapabilities(false);
3690 parametersView.setIgnoreRequirements(false);
3692 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
3694 if (eitherGetResource.isRight()) {
3695 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3697 return Either.right(responseFormat);
3701 resource = eitherGetResource.left().value();
3703 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3704 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3705 ComponentInstance currentCompInstance = null;
3706 for (ComponentInstance compInstance : componentInstancesList) {
3708 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3709 currentCompInstance = compInstance;
3714 if (currentCompInstance == null) {
3715 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3716 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3717 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3718 return Either.right(responseFormat);
3721 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
3722 if (addRelationToRiRes.getStatus() != 200) {
3723 return Either.right(addRelationToRiRes);
3727 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
3728 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3729 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3730 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3731 return Either.right(responseFormat);
3734 log.debug("************* in create relations, getResource start");
3736 eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3737 log.debug("************* in create relations, getResource end");
3738 if (eitherGetResource.isRight()) {
3739 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3741 return Either.right(responseFormat);
3744 resource = eitherGetResource.left().value();
3745 if(resource.getResourceType() == ResourceTypeEnum.CVFC){
3746 eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
3747 if (eitherGetResource.isRight()) {
3748 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3749 return Either.right(responseFormat);
3752 return Either.left(eitherGetResource.left().value());
3755 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3756 Either<Resource, StorageOperationStatus> updateRes = null;
3757 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3758 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3759 StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements( resource.getUniqueId());
3760 if(status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND){
3761 log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", resource.getUniqueId(), status);
3762 updateRes = Either.right(status);
3764 if(updateRes == null){
3765 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities, updatedInstRequirements);
3766 status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource.getUniqueId());
3767 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3768 log.debug("Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", resource.getUniqueId(), status);
3769 updateRes = Either.right(status);
3772 if(updateRes == null){
3773 updateRes = toscaOperationFacade.getToscaElement( resource.getUniqueId());
3779 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3780 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3782 componentInstances.stream().forEach( i -> {
3783 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
3784 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
3788 private void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3789 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3790 Set<String> updatedReqNames = new HashSet<>();
3791 if(MapUtils.isNotEmpty(requirementsNamesToUpdate)){
3792 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
3793 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream()
3794 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3795 .map(r ->{r.setParentName(r.getName()); r.setName(requirementsNamesToUpdate.get(r.getName())); updatedReqNames.add(r.getName()); return r;})
3796 .collect(Collectors.toList()));
3799 if(MapUtils.isNotEmpty(updatedRequirements)){
3800 updatedInstRequirements.put(instance, updatedRequirements);
3804 private void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3805 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3806 Set<String> updatedCapNames = new HashSet<>();
3807 if(MapUtils.isNotEmpty(capabilitiesNamesToUpdate)){
3808 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
3809 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream()
3810 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3811 .map(c -> {c.setParentName(c.getName()); c.setName(capabilitiesNamesToUpdate.get(c.getName())); updatedCapNames.add(c.getName()); return c;})
3812 .collect(Collectors.toList()));
3815 if(MapUtils.isNotEmpty(updatedCapabilities)){
3816 updatedInstCapabilties.put(instance, updatedCapabilities);
3820 private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3821 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3823 UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
3825 ComponentInstance currentCompInstance = null;
3827 for (ComponentInstance compInstance : componentInstancesList) {
3829 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3830 currentCompInstance = compInstance;
3836 if (currentCompInstance == null) {
3837 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3838 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3839 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3840 return responseFormat;
3842 String resourceInstanceId = currentCompInstance.getUniqueId();
3844 Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
3846 if (regMap != null) {
3847 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
3849 while (nodesRegValue.hasNext()) {
3850 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3852 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3853 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3854 log.debug("Going to create relation {}", uploadRegInfo.getName());
3855 String regName = uploadRegInfo.getName();
3856 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3857 regCapRelDef.setFromNode(resourceInstanceId);
3858 log.debug("try to find available requirement {} ", regName);
3859 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
3860 if (eitherReqStatus.isRight()) {
3861 log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
3862 return eitherReqStatus.right().value();
3865 RequirementDefinition validReq = eitherReqStatus.left().value();
3866 List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
3867 if (reqAndRelationshipPairList == null)
3868 reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
3869 RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
3870 reqAndRelationshipPair.setRequirement(regName);
3871 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3872 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3873 RelationshipImpl relationship = new RelationshipImpl();
3874 relationship.setType(validReq.getCapability());
3875 reqAndRelationshipPair.setRelationships(relationship);
3877 ComponentInstance currentCapCompInstance = null;
3878 for (ComponentInstance compInstance : componentInstancesList) {
3879 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
3880 currentCapCompInstance = compInstance;
3885 if (currentCapCompInstance == null) {
3886 log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
3887 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3888 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3889 return responseFormat;
3891 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3892 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3893 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
3894 if (aviableCapForRel == null) {
3895 log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
3896 BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
3897 ErrorSeverity.ERROR);
3898 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3899 return responseFormat;
3901 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3902 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3903 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3904 reqAndRelationshipPairList.add(reqAndRelationshipPair);
3905 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3906 relations.add(regCapRelDef);
3909 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3910 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3911 return responseFormat;
3913 return componentsUtils.getResponseFormat(ActionStatus.OK);
3916 private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3917 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3918 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3919 if (propMap != null && propMap.size() > 0) {
3920 Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
3922 List<InputDefinition> listFromMap = originResource.getInputs();
3923 if (listFromMap == null || listFromMap.isEmpty()) {
3924 log.debug("failed to find properties ");
3925 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3926 return responseFormat;
3928 for (InputDefinition prop : listFromMap) {
3929 String propName = prop.getName();
3930 if (!currPropertiesMap.containsKey(propName)) {
3931 currPropertiesMap.put(propName, prop);
3934 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3935 for (List<UploadPropInfo> propertyList : propMap.values()) {
3937 UploadPropInfo propertyInfo = propertyList.get(0);
3938 String propName = propertyInfo.getName();
3939 if (!currPropertiesMap.containsKey(propName)) {
3940 log.debug("failed to find property {} ", propName);
3941 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3942 return responseFormat;
3944 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3945 ComponentInstanceInput property = null;
3947 String value = null;
3948 List<GetInputValueDataDefinition> getInputs = null;
3949 boolean isValidate = true;
3950 if (propertyInfo.getValue() != null) {
3951 getInputs = propertyInfo.getGet_input();
3952 isValidate = getInputs == null || getInputs.isEmpty();
3954 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3956 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
3958 String innerType = null;
3959 property = new ComponentInstanceInput(curPropertyDef, value, null);
3961 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
3962 if (validatevalueEiter.isRight()) {
3963 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3966 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
3967 // property.setUniqueId(uniqueId);
3968 property.setValue(validatevalueEiter.left().value());
3970 if (getInputs != null && !getInputs.isEmpty()) {
3971 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3972 for (GetInputValueDataDefinition getInput : getInputs) {
3973 List<InputDefinition> inputs = resource.getInputs();
3974 if (inputs == null || inputs.isEmpty()) {
3975 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
3976 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3979 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3980 if (!optional.isPresent()) {
3981 log.debug("Failed to find input {} ", getInput.getInputName());
3982 // @@TODO error message
3983 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3985 InputDefinition input = optional.get();
3986 getInput.setInputId(input.getUniqueId());
3987 getInputValues.add(getInput);
3989 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3990 if (getInputIndex != null) {
3991 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
3992 if (!optional.isPresent()) {
3993 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3994 // @@TODO error message
3995 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3997 InputDefinition inputIndex = optional.get();
3998 getInputIndex.setInputId(inputIndex.getUniqueId());
3999 getInputValues.add(getInputIndex);
4002 property.setGetInputValues(getInputValues);
4004 instPropList.add(property);
4005 // delete overriden property
4006 currPropertiesMap.remove(property.getName());
4008 // add rest of properties
4009 if (!currPropertiesMap.isEmpty()) {
4010 for (InputDefinition value : currPropertiesMap.values()) {
4011 instPropList.add(new ComponentInstanceInput(value));
4014 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
4016 return componentsUtils.getResponseFormat(ActionStatus.OK);
4019 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
4020 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
4022 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
4023 if (propMap != null && propMap.size() > 0) {
4024 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
4026 List<PropertyDefinition> listFromMap = originResource.getProperties();
4027 if (listFromMap == null || listFromMap.isEmpty()) {
4028 log.debug("failed to find properties ");
4029 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
4030 return responseFormat;
4032 for (PropertyDefinition prop : listFromMap) {
4033 String propName = prop.getName();
4034 if (!currPropertiesMap.containsKey(propName)) {
4035 currPropertiesMap.put(propName, prop);
4038 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
4039 for (List<UploadPropInfo> propertyList : propMap.values()) {
4041 UploadPropInfo propertyInfo = propertyList.get(0);
4042 String propName = propertyInfo.getName();
4043 if (!currPropertiesMap.containsKey(propName)) {
4044 log.debug("failed to find property {} ", propName);
4045 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
4046 return responseFormat;
4048 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
4049 ComponentInstanceProperty property = null;
4051 String value = null;
4052 List<GetInputValueDataDefinition> getInputs = null;
4053 boolean isValidate = true;
4054 if (propertyInfo.getValue() != null) {
4055 getInputs = propertyInfo.getGet_input();
4056 isValidate = getInputs == null || getInputs.isEmpty();
4058 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
4060 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
4062 String innerType = null;
4063 property = new ComponentInstanceProperty(curPropertyDef, value, null);
4065 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
4066 if (validatevalueEiter.isRight()) {
4067 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
4070 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
4071 // property.setUniqueId(uniqueId);
4072 property.setValue(validatevalueEiter.left().value());
4074 if (getInputs != null && !getInputs.isEmpty()) {
4075 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
4076 for (GetInputValueDataDefinition getInput : getInputs) {
4077 List<InputDefinition> inputs = resource.getInputs();
4078 if (inputs == null || inputs.isEmpty()) {
4079 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
4080 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4083 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
4084 if (!optional.isPresent()) {
4085 log.debug("Failed to find input {} ", getInput.getInputName());
4086 // @@TODO error message
4087 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4089 InputDefinition input = optional.get();
4090 getInput.setInputId(input.getUniqueId());
4091 getInputValues.add(getInput);
4093 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
4094 if (getInputIndex != null) {
4095 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
4096 if (!optional.isPresent()) {
4097 log.debug("Failed to find input {} ", getInputIndex.getInputName());
4098 // @@TODO error message
4099 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4101 InputDefinition inputIndex = optional.get();
4102 getInputIndex.setInputId(inputIndex.getUniqueId());
4103 getInputValues.add(getInputIndex);
4108 property.setGetInputValues(getInputValues);
4110 instPropList.add(property);
4111 // delete overriden property
4112 currPropertiesMap.remove(property.getName());
4114 // add rest of properties
4115 if (!currPropertiesMap.isEmpty()) {
4116 for (PropertyDefinition value : currPropertiesMap.values()) {
4117 instPropList.add(new ComponentInstanceProperty(value));
4120 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
4122 return componentsUtils.getResponseFormat(ActionStatus.OK);
4125 // US740820 Relate RIs according to capability name
4126 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4127 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
4131 return findAviableCapability(validReq, currentCapCompInstance);
4133 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
4136 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4137 CapabilityDefinition cap = null;
4138 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4139 if (!capMap.containsKey(validReq.getCapability())) {
4142 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
4143 if (!capByName.isPresent()) {
4146 cap = capByName.get();
4148 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4149 String leftOccurrences = cap.getLeftOccurrences();
4150 int left = Integer.parseInt(leftOccurrences);
4153 cap.setLeftOccurrences(String.valueOf(left));
4159 // TODO temporary fix - remove specific capability node validation -
4160 // String reqNode = validReq.getNode();
4161 // if (reqNode != null && !reqNode.isEmpty() &&
4162 // !cap.getCapabilitySources().contains(reqNode)) {
4165 // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
4166 // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
4167 // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
4173 private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
4174 CapabilityDefinition aviableCapForRel = null;
4175 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4176 if (capMap.containsKey(validReq.getCapability())) {
4177 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
4179 for (CapabilityDefinition cap : capList) {
4180 // TODO temporary fix - remove specific capability node
4181 // String reqNode = validReq.getNode();
4182 // if (reqNode != null && !reqNode.isEmpty()) {
4183 // if (!cap.getCapabilitySources().contains(reqNode)) {
4187 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4188 String leftOccurrences = cap.getLeftOccurrences();
4189 if (leftOccurrences == null) {
4190 leftOccurrences = cap.getMaxOccurrences();
4192 int left = Integer.parseInt(leftOccurrences);
4195 cap.setLeftOccurrences(String.valueOf(left));
4196 aviableCapForRel = cap;
4202 aviableCapForRel = cap;
4207 return aviableCapForRel;
4210 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
4211 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
4212 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
4213 RequirementDefinition validRegDef = null;
4215 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
4216 for (RequirementDefinition reqDef : entry.getValue()) {
4217 if (reqDef.getName().equals(regName)) {
4218 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4219 String leftOccurrences = reqDef.getLeftOccurrences();
4220 if (leftOccurrences == null) {
4221 leftOccurrences = reqDef.getMaxOccurrences();
4223 int left = Integer.parseInt(leftOccurrences);
4226 reqDef.setLeftOccurrences(String.valueOf(left));
4227 validRegDef = reqDef;
4233 validRegDef = reqDef;
4239 if (validRegDef != null) {
4244 for (RequirementDefinition reqDef : list) {
4245 if (reqDef.getName().equals(regName)) {
4246 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4247 String leftOccurrences = reqDef.getLeftOccurrences();
4248 if (leftOccurrences == null) {
4249 leftOccurrences = reqDef.getMaxOccurrences();
4251 int left = Integer.parseInt(leftOccurrences);
4254 reqDef.setLeftOccurrences(String.valueOf(left));
4255 validRegDef = reqDef;
4261 validRegDef = reqDef;
4267 if (validRegDef == null) {
4268 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4269 return Either.right(responseFormat);
4271 return Either.left(validRegDef);
4274 public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
4276 Map<String, Object> mappedToscaTemplate;
4277 if(nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)){
4278 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
4282 //DE154502 Fail if duplicate key found in file
4283 mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
4285 } catch(ParserException e) {
4286 log.error("Failed to load yaml file {}", yamlFileName, e);
4287 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, yamlFileName, e.getMessage());
4288 return Either.right(responseFormat);
4291 Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
4292 if (toscaElementEither.isRight()) {
4293 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4294 return Either.right(responseFormat);
4297 Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4298 if (createInputsEither.isRight()) {
4299 ResponseFormat responseFormat = createInputsEither.right().value();
4300 return Either.right(responseFormat);
4303 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
4304 if (uploadResInstancesEither.isRight()) {
4305 ResponseFormat responseFormat = uploadResInstancesEither.right().value();
4306 return Either.right(responseFormat);
4309 Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4310 if (createGroupsFromYaml.isRight()) {
4311 ResponseFormat responseFormat = createGroupsFromYaml.right().value();
4312 return Either.right(responseFormat);
4315 ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
4316 parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
4317 parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
4318 parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
4320 return Either.left(parsedToscaYamlInfo);
4323 private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
4324 Map<String, Resource> nodeNamespaceMap) {
4326 Either<Resource, ResponseFormat> eitherResource = null;
4327 log.debug("{} - going to create resource instanse from CSAR", yamlName);
4328 if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
4329 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4331 return Either.right(responseFormat);
4334 Map<String, Resource> existingnodeTypeMap = new HashMap<>();
4335 if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) {
4336 nodeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
4339 Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
4340 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
4341 while (nodesInfoValue.hasNext()) {
4342 log.debug("*************Going to create resource instances from {}", yamlName);
4343 Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
4344 UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
4346 // updating type if the type is node type name - we need to take the
4348 log.debug("*************Going to create resource instance {}", uploadComponentInstanceInfo.getName());
4349 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4350 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
4353 eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
4354 if (eitherResource.isRight()) {
4355 return eitherResource;
4357 Resource refResource = eitherResource.left().value();
4359 ComponentInstance componentInstance = new ComponentInstance();
4361 componentInstance.setComponentUid(refResource.getUniqueId());
4363 ComponentTypeEnum containerComponentType = resource.getComponentType();
4364 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
4366 if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils.isNotEmpty(refResource.getCapabilities())) {
4367 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4368 Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4369 if (getValidComponentInstanceCapabilitiesRes.isRight()) {
4370 return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
4372 componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
4375 //***********************
4376 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
4377 log.debug("createResourceInstances - not found latest version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4378 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4379 return Either.right(responseFormat);
4381 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
4382 componentInstance.setName(uploadComponentInstanceInfo.getName());
4383 componentInstance.setIcon(origResource.getIcon());
4385 resourcesInstancesMap.put(componentInstance, origResource);
4388 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
4390 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
4391 if (status != null && status != StorageOperationStatus.OK) {
4392 log.debug("Failed to add component instances to container component {}", resource.getName());
4393 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
4394 eitherResource = Either.right(responseFormat);
4395 return eitherResource;
4400 log.debug("*************Going to get resource {}", resource.getUniqueId());
4401 ComponentParametersView parametersView = new ComponentParametersView();
4402 parametersView.disableAll();
4403 parametersView.setIgnoreComponentInstances(false);
4404 parametersView.setIgnoreUsers(false);
4405 parametersView.setIgnoreInputs(false); // inputs are read when creating
4406 // property values on instances
4407 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
4408 log.debug("*************finished to get resource {}", resource.getUniqueId());
4409 if (eitherGerResource.isRight()) {
4410 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
4412 return Either.right(responseFormat);
4416 if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
4418 log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
4419 BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty");
4420 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4421 return Either.right(responseFormat);
4425 return Either.left(eitherGerResource.left().value());
4428 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4429 for(Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()){
4430 if(originCapabilities.containsKey(currEntry.getKey())){
4431 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
4435 for(Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()){
4436 capabilities.getValue().stream().forEach(cap -> {if(uploadedCapabilities.containsKey(cap.getName())){uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {c.setName(cap.getName());c.setType(cap.getType());});};});
4442 private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
4443 log.debug("going to validate resource instance with name {} and type {} before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4444 Resource refResource = null;
4445 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4446 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
4448 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
4449 if (findResourceEither.isRight()) {
4450 log.debug("not found lates version for resource instance with name {} and type {}", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4451 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
4452 return Either.right(responseFormat);
4454 refResource = findResourceEither.left().value();
4455 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
4457 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
4458 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4459 log.debug("component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState);
4460 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
4461 return Either.right(responseFormat);
4464 if (!ToscaUtils.isAtomicType(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
4465 log.debug("ref resource type is {}", refResource.getResourceType());
4466 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4467 return Either.right(responseFormat);
4469 log.debug("validate resource instance with name {} and type {} before create, successful",uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4470 return Either.left(refResource);
4473 private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) {
4474 Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
4475 Map<String, Object> substitutionMappings = null;
4476 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
4477 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
4478 Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
4479 if (eitherSubstitutionMappings.isLeft()) {
4480 substitutionMappings = eitherSubstitutionMappings.left().value();
4482 if (eitherNodesTemlates.isLeft()) {
4483 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
4485 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
4486 while (nodesNameValue.hasNext()) {
4487 Entry<String, Object> nodeNameValue = nodesNameValue.next();
4488 Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
4489 if (eitherNode.isRight()) {
4490 log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
4491 return Either.right(eitherNode.right().value());
4493 UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
4494 moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
4500 if (moduleComponentInstances.isEmpty()) {
4501 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
4502 return Either.right(responseFormat);
4508 @SuppressWarnings("unchecked")
4509 private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) {
4511 UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
4512 Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
4513 nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
4515 if (nodeTemplateJsonEntry.getValue() instanceof String) {
4516 String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
4517 nodeTemplateInfo.setType(nodeTemplateJsonString);
4518 } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
4519 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
4521 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4522 String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
4523 if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
4524 toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
4526 nodeTemplateInfo.setType(toscaResourceType);
4529 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4530 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4531 if (regResponse.isRight())
4532 return Either.right(regResponse.right().value());
4533 if (regResponse.left().value().size() > 0) {
4534 nodeTemplateInfo.setRequirements(regResponse.left().value());
4538 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4539 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4540 if (eitherCapRes.isRight())
4541 return Either.right(eitherCapRes.right().value());
4542 if (eitherCapRes.left().value().size() > 0) {
4543 nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
4546 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4547 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4548 if (regResponse.isRight())
4549 return Either.right(regResponse.right().value());
4550 if (regResponse.left().value().size() > 0) {
4551 nodeTemplateInfo.setProperties(regResponse.left().value());
4554 if (substitutionMappings != null) {
4555 if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4556 Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
4557 if (getCapNamesToUpdateRes.isRight())
4558 return Either.right(getCapNamesToUpdateRes.right().value());
4559 if (getCapNamesToUpdateRes.left().value().size() > 0) {
4560 nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
4563 if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4564 Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
4565 if (getReqNamesToUpdateRes.isRight())
4566 return Either.right(getReqNamesToUpdateRes.right().value());
4567 if (getReqNamesToUpdateRes.left().value().size() > 0) {
4568 nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
4574 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
4577 } catch (Exception e) {
4578 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
4579 log.debug("error when creating capability, message:{}", e.getMessage(), e);
4580 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
4586 private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) {
4587 Either<Map<String, String>, ResponseFormat> response;
4589 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()));
4590 response = Either.left(namesToUpdate);
4591 } catch (Exception e) {
4592 log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName());
4593 response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4598 @SuppressWarnings("unchecked")
4599 private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
4600 Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
4601 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
4602 Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
4603 if (toscaProperties.isLeft()) {
4604 Map<String, Object> jsonProperties = toscaProperties.left().value();
4605 for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
4607 String propName = jsonPropObj.getKey();
4608 Object propValue = jsonPropObj.getValue();
4610 if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
4611 log.trace("Ignore property value {}.", propName);
4615 if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
4616 log.trace("Ignore property value {}.", propName);
4619 if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
4620 log.trace("Ignore property value {}.", propName);
4624 if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
4625 log.trace("Ignore property value {}.", propName);
4629 UploadPropInfo propertyDef = new UploadPropInfo();
4630 propertyDef.setValue(propValue);
4631 propertyDef.setName(propName);
4632 if (propValue instanceof Map) {
4633 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4634 propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
4637 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
4638 || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4639 createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
4642 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
4643 propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
4645 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
4646 propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
4648 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
4649 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
4651 propertyDef.setValue(propValue);
4653 } else if (propValue instanceof List) {
4654 List<Object> propValueList = (List<Object>) propValue;
4656 createInputPropList(propertyDef, propValueList);
4657 propertyDef.setValue(propValue);
4660 if (moduleProp.containsKey(propName)) {
4661 moduleProp.get(propName).add(propertyDef);
4663 List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
4664 list.add(propertyDef);
4665 moduleProp.put(propName, list);
4672 @SuppressWarnings("unchecked")
4673 private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
4674 for (Object objValue : propValueList) {
4676 if (objValue instanceof Map) {
4677 Map<String, Object> objMap = (Map<String, Object>) objValue;
4678 if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
4679 createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
4681 Set<String> keys = objMap.keySet();
4682 for (String key : keys) {
4683 Object value = objMap.get(key);
4684 if (value instanceof Map) {
4685 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4687 } else if (value instanceof List) {
4688 List<Object> propSubValueList = (List<Object>) value;
4690 createInputPropList(propertyDef, propSubValueList);
4696 } else if (objValue instanceof List) {
4697 List<Object> propSubValueList = (List<Object>) objValue;
4699 createInputPropList(propertyDef, propSubValueList);
4706 @SuppressWarnings("unchecked")
4707 private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
4709 if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4710 Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4711 GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
4712 List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
4713 if (getInputs == null) {
4714 getInputs = new ArrayList<GetInputValueDataDefinition>();
4716 if (getInput instanceof String) {
4718 getInputInfo.setInputName((String) getInput);
4719 getInputInfo.setPropName(propName);
4721 } else if (getInput instanceof List) {
4722 List<Object> getInputList = (List<Object>) getInput;
4723 getInputInfo.setPropName(propName);
4724 getInputInfo.setInputName((String) getInputList.get(0));
4725 if (getInputList.size() > 1) {
4726 Object indexObj = getInputList.get(1);
4727 if (indexObj instanceof Integer) {
4728 getInputInfo.setIndexValue((Integer) indexObj);
4729 } else if (indexObj instanceof Float) {
4730 int index = ((Float) indexObj).intValue();
4731 getInputInfo.setIndexValue(index);
4732 } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4733 Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4734 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
4735 getInputInfoIndex.setInputName((String) index);
4736 getInputInfoIndex.setPropName(propName);
4737 getInputInfo.setGetInputIndex(getInputInfoIndex);
4739 getInputInfo.setList(true);
4743 getInputs.add(getInputInfo);
4744 propertyDef.setGet_input(getInputs);
4745 propertyDef.setValue(propValue);
4747 Set<String> keys = propValue.keySet();
4748 for (String key : keys) {
4749 Object value = propValue.get(key);
4750 if (value instanceof Map) {
4751 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4753 } else if (value instanceof List) {
4754 List<Object> valueList = (List<Object>) value;
4755 for (Object o : valueList) {
4756 if (o instanceof Map) {
4757 createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
4770 * private boolean valueContainsStrReplace(Object propValue) {
4772 * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher =
4773 * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); }
4777 * private boolean valueContainsToken(Object propValue) {
4779 * 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 =
4785 private boolean valueContainsPattern(Pattern pattern, Object propValue) {
4787 log.debug("valueContainsToken value is {}", propValue);
4788 boolean result = false;
4789 if (propValue != null) {
4790 log.trace("valueContainspattern value is {}", propValue.getClass());
4791 Matcher matcher = pattern.matcher(propValue.toString());
4792 result = matcher.find();
4799 @SuppressWarnings("unchecked")
4800 private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4801 Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
4802 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
4803 Either<List<Object>, ResultStatusEnum> capabilitiesListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4804 if (capabilitiesListRes.isLeft()) {
4805 for (Object jsonCapObj : capabilitiesListRes.left().value()) {
4806 String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next();
4807 Object capJson = ((Map<String, Object>) jsonCapObj).get(key);
4808 Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, key);
4809 if (eitherCap.isRight()) {
4810 return Either.right(eitherCap.right().value());
4814 Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4815 if (capabilitiesMapRes.isLeft()) {
4816 for (Map.Entry<String, Object> entry : capabilitiesMapRes.left().value().entrySet()) {
4817 String capName = entry.getKey();
4818 Object capJson = entry.getValue();
4819 Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, capName);
4820 if (eitherCap.isRight()) {
4821 return Either.right(eitherCap.right().value());
4829 private Either<UploadCapInfo, ResponseFormat> addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
4831 Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJson);
4832 if (eitherCap.isRight()) {
4833 log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo);
4834 return Either.right(eitherCap.right().value());
4836 UploadCapInfo capabilityDef = eitherCap.left().value();
4837 capabilityDef.setKey(key);
4838 if (moduleCap.containsKey(key)) {
4839 moduleCap.get(key).add(capabilityDef);
4841 List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
4842 list.add(capabilityDef);
4843 moduleCap.put(key, list);
4846 return Either.left( eitherCap.left().value());
4849 @SuppressWarnings("unchecked")
4850 private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4851 Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
4852 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
4853 Either<List<Object>, ResultStatusEnum> requirementsListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4855 if (requirementsListRes.isLeft()) {
4856 for (Object jsonReqObj : requirementsListRes.left().value()) {
4857 String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
4858 Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName);
4859 Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName);
4860 if (eitherCap.isRight()) {
4861 return Either.right(eitherCap.right().value());
4865 Either<Map<String,Object>, ResultStatusEnum> requirementsMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4866 if (requirementsMapRes.isLeft()) {
4867 for (Map.Entry<String, Object> entry: requirementsMapRes.left().value().entrySet()) {
4868 String reqName = entry.getKey();
4869 Object reqJson = entry.getValue();
4870 Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName);
4871 if (eitherCap.isRight()) {
4872 return Either.right(eitherCap.right().value());
4880 private Either<UploadReqInfo, ResponseFormat> addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) {
4882 Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJson);
4883 if (eitherRequirement.isRight()) {
4884 log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
4885 return Either.right(eitherRequirement.right().value());
4887 UploadReqInfo requirementDef = eitherRequirement.left().value();
4888 requirementDef.setName(requirementName);
4889 if (moduleRequirements.containsKey(requirementName)) {
4890 moduleRequirements.get(requirementName).add(requirementDef);
4892 List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
4893 list.add(requirementDef);
4894 moduleRequirements.put(requirementName, list);
4897 return Either.left(eitherRequirement.left().value());
4900 @SuppressWarnings("unchecked")
4901 private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
4902 UploadCapInfo capTemplateInfo = new UploadCapInfo();
4903 Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
4905 if (capObject instanceof String) {
4906 String nodeTemplateJsonString = (String) capObject;
4907 capTemplateInfo.setNode(nodeTemplateJsonString);
4908 } else if (capObject instanceof Map) {
4909 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
4911 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4912 capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4914 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4915 capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4917 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
4918 Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
4919 if (validSourceTypesRes.isLeft()) {
4920 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList()));
4923 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4924 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4925 if (regResponse.isRight())
4926 return Either.right(regResponse.right().value());
4927 if (!regResponse.left().value().isEmpty()) {
4928 List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
4929 regResponse.left().value().values().forEach(list -> properties.addAll(list));
4930 if (!properties.isEmpty())
4931 capTemplateInfo.setProperties(properties);
4938 @SuppressWarnings("unchecked")
4939 private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
4941 UploadReqInfo regTemplateInfo = new UploadReqInfo();
4942 Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
4944 if (regObject instanceof String) {
4945 String nodeTemplateJsonString = (String) regObject;
4946 regTemplateInfo.setNode(nodeTemplateJsonString);
4947 } else if (regObject instanceof Map) {
4948 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
4950 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4951 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4953 // US740820 Relate RIs according to capability name
4954 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
4955 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
4961 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) {
4963 Either<Resource, ResponseFormat> result = null;
4965 if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())){
4966 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4967 if(result.isRight()){
4970 resource = result.left().value();
4972 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
4973 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
4974 result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
4977 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
4978 } catch (Exception e) {
4979 log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName());
4980 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4982 if (result == null || result.isRight()) {
4983 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4984 if (inTransaction == false) {
4985 log.debug("operation failed. do rollback");
4986 titanDao.rollback();
4988 } else if (inTransaction == false) {
4989 log.debug("operation success. do commit");
4995 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4996 Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
4997 if (result.isLeft()) {
4998 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
5000 if (result.isLeft()) {
5001 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
5006 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
5007 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
5013 * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
5016 * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
5017 * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
5020 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo) {
5022 // check if resource already exist
5023 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
5024 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
5027 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
5029 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
5030 if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
5031 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
5034 StorageOperationStatus status = latestByName.right().value();
5035 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5036 log.debug("resource already exist {}. status={}", resource.getName(), status);
5037 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
5038 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
5039 result = Either.right(responseFormat);
5045 else if (latestByName.isLeft()) {
5046 result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock);
5051 StorageOperationStatus status = latestByName.right().value();
5052 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
5053 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
5054 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
5055 result = Either.right(responseFormat);
5061 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
5062 log.debug("resource with name {} does not exist. create new resource", resource.getName());
5063 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
5064 if (response.isRight()) {
5065 return Either.right(response.right().value());
5067 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
5068 if (createResponse.isRight()) {
5069 return Either.right(createResponse.right().value());
5071 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
5072 ASDCKpiApi.countImportResourcesKPI();
5073 return Either.left(resourcePair);
5078 public boolean isResourceExist(String resourceName) {
5079 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
5080 return latestByName.isLeft();
5083 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock) {
5084 String lockedResourceId = oldResource.getUniqueId();
5085 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState());
5086 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
5089 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import");
5090 if (lockResult.isRight()) {
5091 return Either.right(lockResult.right().value());
5095 Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false);
5096 if (prepareResourceForUpdate.isRight()) {
5097 ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
5098 log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage());
5099 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5100 result = Either.right(prepareResourceForUpdate.right().value());
5103 oldResource = prepareResourceForUpdate.left().value();
5105 mergeOldResourceMetadataWithNew(oldResource, newResource);
5107 Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction);
5108 if (validateFieldsResponse.isRight()) {
5109 result = Either.right(validateFieldsResponse.right().value());
5113 // contact info normalization
5114 newResource.setContactId(newResource.getContactId().toLowerCase());
5115 // non-updatable fields
5116 newResource.setCreatorUserId(user.getUserId());
5117 newResource.setCreatorFullName(user.getFullName());
5118 newResource.setLastUpdaterUserId(user.getUserId());
5119 newResource.setLastUpdaterFullName(user.getFullName());
5120 newResource.setUniqueId(oldResource.getUniqueId());
5121 newResource.setVersion(oldResource.getVersion());
5122 newResource.setInvariantUUID(oldResource.getInvariantUUID());
5123 newResource.setLifecycleState(oldResource.getLifecycleState());
5124 newResource.setUUID(oldResource.getUUID());
5125 newResource.setNormalizedName(oldResource.getNormalizedName());
5126 newResource.setSystemName(oldResource.getSystemName());
5127 if (oldResource.getCsarUUID() != null) {
5128 newResource.setCsarUUID(oldResource.getCsarUUID());
5130 if (oldResource.getImportedToscaChecksum() != null) {
5131 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
5133 newResource.setAbstract(oldResource.isAbstract());
5135 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
5136 newResource.setDerivedFrom(oldResource.getDerivedFrom());
5138 // TODO rhalili: handle artifacts here (delete from old resource and
5140 // TODO rbetzer: remove after migration - in case of resources
5141 // created without tosca artifacts - add the placeholders
5142 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
5143 setToscaArtifactsPlaceHolders(newResource, user);
5145 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
5147 if (overrideResource.isRight()) {
5148 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
5149 componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5150 result = Either.right(responseFormat);
5154 log.debug("Resource updated successfully!!!");
5155 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
5156 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5158 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
5159 result = Either.left(resourcePair);
5162 if (result == null || result.isRight()) {
5163 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
5164 log.debug("operation failed. do rollback");
5165 titanDao.rollback();
5166 } else if (inTransaction == false) {
5167 log.debug("operation success. do commit");
5170 if (needLock == true) {
5171 log.debug("unlock resource {}", lockedResourceId);
5172 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
5179 * Merge old resource with new. Keep old category and vendor name without change
5181 * @param oldResource
5182 * @param newResource
5184 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
5186 // keep old category and vendor name without change
5187 // merge the rest of the resource metadata
5188 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
5189 newResource.setTags(oldResource.getTags());
5192 if (newResource.getDescription() == null) {
5193 newResource.setDescription(oldResource.getDescription());
5196 if (newResource.getVendorRelease() == null) {
5197 newResource.setVendorRelease(oldResource.getVendorRelease());
5200 if (newResource.getResourceVendorModelNumber() == null) {
5201 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
5204 if (newResource.getContactId() == null) {
5205 newResource.setContactId(oldResource.getContactId());
5208 newResource.setCategories(oldResource.getCategories());
5209 newResource.setVendorName(oldResource.getVendorName());
5212 private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) {
5214 Either<Resource, ResponseFormat> result = Either.left(latestResource);
5215 // check if user can edit resource
5216 if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
5218 Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
5219 result = changeState;
5225 public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
5227 Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
5228 if (eitherValidation.isRight()) {
5229 return Either.right(eitherValidation.right().value());
5232 eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
5233 if (eitherValidation.isRight()) {
5234 return Either.right(eitherValidation.right().value());
5236 eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
5237 if (eitherValidation.isRight()) {
5238 return Either.right(eitherValidation.right().value());
5240 eitherValidation = validateResourceType(user, resource, actionEnum);
5241 if (eitherValidation.isRight()) {
5242 return Either.right(eitherValidation.right().value());
5245 resource.setCreatorUserId(user.getUserId());
5246 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
5247 resource.setContactId(resource.getContactId().toLowerCase());
5248 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ToscaUtils.isAtomicType(resource)) {
5249 String resourceSystemName;
5250 if(csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())){
5251 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
5253 resourceSystemName = resource.getSystemName();
5255 resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
5258 // Generate invariant UUID - must be here and not in operation since it
5259 // should stay constant during clone
5261 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
5262 resource.setInvariantUUID(invariantUUID);
5264 return Either.left(resource);
5267 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
5268 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5269 if (resource.getResourceType() == null) {
5270 log.debug("Invalid resource type for resource");
5271 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5272 eitherResult = Either.right(errorResponse);
5273 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5275 return eitherResult;
5278 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
5279 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5280 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
5281 log.debug("validate interface lifecycle Types Exist");
5282 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
5283 while (intItr.hasNext() && eitherResult.isLeft()) {
5284 InterfaceDefinition interfaceDefinition = intItr.next();
5285 String intType = interfaceDefinition.getUniqueId();
5286 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
5287 if (eitherCapTypeFound.isRight()) {
5288 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5289 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
5290 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
5291 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
5292 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
5295 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
5296 eitherResult = Either.right(errorResponse);
5297 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5302 return eitherResult;
5305 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5307 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5308 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
5309 log.debug("validate capability Types Exist - capabilities section");
5311 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
5313 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
5314 if (eitherResult.isRight()) {
5315 return Either.right(eitherResult.right().value());
5320 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
5321 log.debug("validate capability Types Exist - requirements section");
5322 for (String type : resource.getRequirements().keySet()) {
5323 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
5324 if (eitherResult.isRight()) {
5325 return Either.right(eitherResult.right().value());
5330 return eitherResult;
5333 // @param typeObject- the object to which the validation is done
5334 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
5335 boolean inTransaction) {
5336 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
5337 if (eitherCapTypeFound.isRight()) {
5338 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5339 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
5340 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
5341 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5343 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
5344 ResponseFormat errorResponse = null;
5346 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
5348 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
5349 eitherResult = Either.right(errorResponse);
5350 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5352 return eitherResult;
5355 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
5356 Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
5357 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
5358 if (eitherCapTypeFound.isRight()) {
5359 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5360 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
5361 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
5362 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5364 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
5365 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
5366 eitherResult = Either.right(errorResponse);
5367 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5369 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
5370 if (capabilityTypeDefinition.getProperties() != null) {
5371 for (CapabilityDefinition capDef : typeEntry.getValue()) {
5372 List<ComponentInstanceProperty> properties = capDef.getProperties();
5373 if (properties == null || properties.isEmpty()) {
5374 properties = new ArrayList<ComponentInstanceProperty>();
5375 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5376 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
5377 properties.add(newProp);
5380 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5381 PropertyDefinition porpFromDef = prop.getValue();
5382 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
5383 for (ComponentInstanceProperty cip : properties) {
5384 if (!cip.getName().equals(porpFromDef.getName())) {
5385 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
5386 propsToAdd.add(newProp);
5389 if (!propsToAdd.isEmpty()) {
5390 properties.addAll(propsToAdd);
5394 capDef.setProperties(properties);
5397 return eitherResult;
5400 public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5403 // lock new resource name in order to avoid creation resource with same
5405 if (inTransaction == false) {
5406 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
5407 if (lockResult.isRight()) {
5408 ResponseFormat responseFormat = lockResult.right().value();
5409 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
5410 return Either.right(responseFormat);
5413 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
5416 if (resource.deriveFromGeneric()) {
5417 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
5418 if (genericResourceEither.isRight())
5419 return genericResourceEither;
5420 if (resource.shouldGenerateInputs())
5421 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
5424 Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
5425 if (respStatus.isLeft()) {
5426 auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams);
5427 ASDCKpiApi.countCreatedResourcesKPI();
5429 componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
5433 if (inTransaction == false) {
5434 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
5439 private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5440 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
5441 componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams);
5444 private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
5445 // validate resource name uniqueness
5446 log.debug("validate resource name");
5447 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
5448 if (eitherValidation.isRight()) {
5449 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
5450 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
5451 return Either.right(errorResponse);
5453 if (eitherValidation.left().value()) {
5454 log.debug("resource with name: {}, already exists", resource.getName());
5455 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5456 return Either.right(errorResponse);
5459 log.debug("send resource {} to dao for create", resource.getName());
5461 createArtifactsPlaceHolderData(resource, user);
5467 log.debug("enrich resource with creator, version and state");
5468 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
5469 resource.setVersion(INITIAL_VERSION);
5470 resource.setHighestVersion(true);
5471 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
5472 resource.setAbstract(false);
5475 Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
5476 if (createToscaElement.isLeft()) {
5477 return Either.left(createToscaElement.left().value());
5480 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
5482 return Either.right(responseFormat);
5485 private void createArtifactsPlaceHolderData(Resource resource, User user) {
5486 // create mandatory artifacts
5488 // TODO it must be removed after that artifact uniqueId creation will be
5489 // moved to ArtifactOperation
5490 // String resourceUniqueId =
5491 // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
5492 // resource.getResourceVersion());
5494 setInformationalArtifactsPlaceHolder(resource, user);
5495 setDeploymentArtifactsPlaceHolder(resource, user);
5496 setToscaArtifactsPlaceHolders(resource, user);
5499 @SuppressWarnings("unchecked")
5501 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
5502 Resource resource = (Resource) component;
5503 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
5504 if (artifactMap == null) {
5505 artifactMap = new HashMap<String, ArtifactDefinition>();
5507 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts();
5508 if (deploymentResourceArtifacts != null) {
5509 Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
5510 while (iterator.hasNext()) {
5511 Entry<String, Object> currEntry = iterator.next();
5512 boolean shouldCreateArtifact = true;
5513 Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
5514 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
5515 if (object != null) {
5516 List<String> artifactTypes = (List<String>) object;
5517 if (!artifactTypes.contains(resource.getResourceType().name())) {
5518 shouldCreateArtifact = false;
5522 log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey());
5524 if (shouldCreateArtifact) {
5525 if (artifactsBusinessLogic != null) {
5526 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT);
5527 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
5528 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5533 resource.setDeploymentArtifacts(artifactMap);
5536 @SuppressWarnings("unchecked")
5537 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
5538 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
5539 if (artifactMap == null) {
5540 artifactMap = new HashMap<String, ArtifactDefinition>();
5542 String resourceUniqueId = resource.getUniqueId();
5543 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
5544 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
5545 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
5546 List<CategoryDefinition> categories = resource.getCategories();
5547 boolean isCreateArtifact = true;
5548 if (exludeResourceCategory != null) {
5549 String category = categories.get(0).getName();
5550 for (String exlude : exludeResourceCategory) {
5551 if (exlude.equalsIgnoreCase(category)) {
5552 isCreateArtifact = false;
5558 if (isCreateArtifact && exludeResourceType != null) {
5559 String resourceType = resource.getResourceType().name();
5560 for (String type : exludeResourceType) {
5561 if (type.equalsIgnoreCase(resourceType)) {
5562 isCreateArtifact = false;
5569 if (informationalResourceArtifacts != null && isCreateArtifact) {
5570 Set<String> keys = informationalResourceArtifacts.keySet();
5571 for (String informationalResourceArtifactName : keys) {
5572 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
5573 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
5574 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5578 resource.setArtifacts(artifactMap);
5588 public ResponseFormat deleteResource(String resourceId, User user) {
5589 ResponseFormat responseFormat;
5590 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5591 if (eitherCreator.isRight()) {
5592 return eitherCreator.right().value();
5595 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
5596 if (resourceStatus.isRight()) {
5597 log.debug("failed to get resource {}", resourceId);
5598 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
5601 Resource resource = resourceStatus.left().value();
5603 StorageOperationStatus result = StorageOperationStatus.OK;
5604 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
5605 if (lockResult.isRight()) {
5606 result = StorageOperationStatus.GENERAL_ERROR;
5607 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5612 result = markComponentToDelete(resource);
5613 if (result.equals(StorageOperationStatus.OK)) {
5614 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5616 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5617 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5619 return responseFormat;
5622 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5623 log.warn("operation failed. do rollback");
5624 titanDao.rollback();
5626 log.debug("operation success. do commit");
5629 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
5634 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
5635 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5636 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5637 if (eitherCreator.isRight()) {
5638 return eitherCreator.right().value();
5641 // Resource resource = null;
5642 Resource resource = null;
5643 StorageOperationStatus result = StorageOperationStatus.OK;
5646 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
5647 if (resourceStatus.isRight()) {
5648 log.debug("failed to get resource {} version {}", resourceName, version);
5649 return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
5652 resource = resourceStatus.left().value();
5655 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5656 log.warn("operation failed. do rollback");
5657 titanDao.rollback();
5658 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5659 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
5661 log.debug("operation success. do commit");
5665 if (resource != null) {
5666 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
5667 if (lockResult.isRight()) {
5668 result = StorageOperationStatus.GENERAL_ERROR;
5669 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5672 result = markComponentToDelete(resource);
5673 if (!result.equals(StorageOperationStatus.OK)) {
5674 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5675 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5676 return responseFormat;
5680 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5681 log.warn("operation failed. do rollback");
5682 titanDao.rollback();
5684 log.debug("operation success. do commit");
5687 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
5690 return responseFormat;
5693 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
5696 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
5697 if (eitherCreator.isRight()) {
5698 return Either.right(eitherCreator.right().value());
5702 // IResourceOperation dataModel = getResourceOperation();
5703 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
5704 if (storageStatus.isRight()) {
5705 log.debug("failed to get resource by id {}", resourceId);
5706 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
5708 if(!(storageStatus.left().value() instanceof Resource)){
5709 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
5711 return Either.left(storageStatus.left().value());
5715 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
5717 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
5718 if (resp.isRight()) {
5719 return Either.right(resp.right().value());
5722 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
5723 if (getResource.isRight()) {
5724 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
5725 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
5727 return Either.left(getResource.left().value());
5731 * updateResourceMetadata
5733 * @param user - modifier data (userId)
5734 * @param inTransaction TODO
5735 * @param resourceIdToUpdate - the resource identifier
5736 * @param newResource
5737 * @return Either<Resource, responseFormat>
5739 public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
5741 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
5742 if (resp.isRight()) {
5743 return Either.right(resp.right().value());
5746 // IResourceOperation dataModel = getResourceOperation();
5747 log.debug("Get resource with id {}", resourceIdToUpdate);
5748 boolean needToUnlock = false;
5749 boolean rollbackNeeded = true;
5752 // Either<Resource, StorageOperationStatus> storageStatus =
5753 // dataModel.getResource_tx(resourceIdToUpdate, false);
5754 if (currentResource == null) {
5755 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
5756 if (storageStatus.isRight()) {
5757 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5760 currentResource = storageStatus.left().value();
5762 // verify that resource is checked-out and the user is the last
5764 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
5765 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
5769 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5770 if (!lockResult.equals(StorageOperationStatus.OK)) {
5771 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
5772 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
5773 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
5774 return Either.right(responseFormat);
5777 needToUnlock = true;
5779 // critical section starts here
5780 // convert json to object
5782 // Update and updated resource must have a non-empty "derivedFrom"
5784 // This code is not called from import resources, because of root
5785 // VF "derivedFrom" should be null (or ignored)
5786 if (ToscaUtils.isAtomicType(currentResource)) {
5787 Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
5788 if (derivedFromNotEmptyEither.isRight()) {
5789 log.debug("for updated resource {}, derived from field is empty", newResource.getName());
5790 return Either.right(derivedFromNotEmptyEither.right().value());
5793 derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
5794 if (derivedFromNotEmptyEither.isRight()) {
5795 log.debug("for current resource {}, derived from field is empty", currentResource.getName());
5796 return Either.right(derivedFromNotEmptyEither.right().value());
5799 newResource.setDerivedFrom(null);
5802 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true);
5803 if (dataModelResponse.isRight()) {
5804 log.debug("failed to update resource metadata!!!");
5805 rollbackNeeded = true;
5806 return Either.right(dataModelResponse.right().value());
5809 log.debug("Resource metadata updated successfully!!!");
5810 rollbackNeeded = false;
5811 return Either.left(dataModelResponse.left().value());
5814 if (!inTransaction) {
5815 if (rollbackNeeded) {
5816 titanDao.rollback();
5823 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5828 private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){
5829 if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){
5830 if (log.isInfoEnabled())
5831 log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" );
5832 return Either.right(false);
5834 List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList());
5835 for ( GroupDefinition group : list) {
5836 if ( group!=null && group.isSamePrefix( replacePattern ) ){
5837 String prefix = group.getName().substring( 0, replacePattern.length() );
5838 String newGroupName = group.getName().replaceFirst(prefix , with);
5839 group.setName(newGroupName);
5840 //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id
5841 //group.setUniqueId(newUid);
5844 return Either.left(list);
5847 private boolean isComponentNameChanged(Resource newResource,Resource oldResource){
5848 if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional
5849 String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5850 String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5851 return !oldName.equals(futureName);
5856 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
5857 //region -> Update groups name for newResource
5858 if ( isComponentNameChanged( currentResource , newResource) ){
5859 String replacePattern = Optional.ofNullable( //get currentResource name from metadata
5860 Optional.ofNullable( Optional.ofNullable( currentResource )
5861 .orElse(null).getComponentMetadataDefinition() )
5862 .orElse(null).getMetadataDataDefinition() )
5863 .orElse(null).getName();
5864 String with = Optional.ofNullable( //get newResource name from metadata
5865 Optional.ofNullable( Optional.ofNullable( newResource )
5866 .orElse(null).getComponentMetadataDefinition() )
5867 .orElse(null).getMetadataDataDefinition() )
5868 .orElse(null).getName();
5869 if ( with != null && replacePattern != null ){
5870 Either<List<GroupDefinition>,Boolean> result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups());
5871 if (result.isLeft())
5872 newResource.setGroups( (List<GroupDefinition>)result.left().value() );
5877 Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
5878 if (validateResourceFields.isRight()) {
5879 return Either.right(validateResourceFields.right().value());
5881 // Setting last updater and uniqueId
5882 newResource.setContactId(newResource.getContactId().toLowerCase());
5883 newResource.setLastUpdaterUserId(user.getUserId());
5884 newResource.setUniqueId(resourceIdToUpdate);
5885 // Cannot set highest version through UI
5886 newResource.setHighestVersion(currentResource.isHighestVersion());
5887 newResource.setCreationDate(currentResource.getCreationDate());
5889 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
5891 if (processUpdateOfDerivedFrom.isRight()) {
5892 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
5893 return Either.right(processUpdateOfDerivedFrom.right().value());
5896 log.debug("send resource {} to dao for update", newResource.getUniqueId());
5897 if (newResource!=null && newResource.getGroups()!=null){
5898 for ( GroupDefinition group : newResource.getGroups() ){
5899 if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null)
5900 groupBusinessLogic.validateAndUpdateGroupMetadata(
5901 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() ,
5903 ComponentTypeEnum.RESOURCE_INSTANCE,
5909 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
5911 if (dataModelResponse.isRight()) {
5912 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
5913 return Either.right(responseFormat);
5914 } else if (dataModelResponse.left().value() == null) {
5915 log.debug("No response from updateResource");
5916 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5918 return Either.left(dataModelResponse.left().value());
5922 * validateResourceFieldsBeforeCreate
5924 * @param user - modifier data (userId)
5925 * @param dataModel - IResourceOperation for resource crud
5926 * @param resource - Resource object to validate
5927 * @return Either<Boolean, ErrorResponse>
5929 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5930 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
5931 if (componentsFieldsValidation.isRight()) {
5932 return componentsFieldsValidation;
5938 * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5940 * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5945 * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5950 * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5953 // validate category
5954 log.debug("validate category");
5955 Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
5956 if (eitherValidation.isRight()) {
5957 return eitherValidation;
5960 // validate vendor name & release & model number
5961 log.debug("validate vendor name");
5962 eitherValidation = validateVendorName(user, resource, actionEnum);
5963 if (eitherValidation.isRight()) {
5964 return eitherValidation;
5967 log.debug("validate vendor release");
5968 eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
5969 if (eitherValidation.isRight()) {
5970 return eitherValidation;
5973 log.debug("validate resource vendor model number");
5974 eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
5975 if (eitherValidation.isRight()) {
5976 return eitherValidation;
5979 // validate contact info
5981 * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5985 log.debug("validate cost");
5986 eitherValidation = validateCost(user, resource, actionEnum);
5987 if (eitherValidation.isRight()) {
5988 return eitherValidation;
5991 // validate licenseType
5992 log.debug("validate licenseType");
5993 eitherValidation = validateLicenseType(user, resource, actionEnum);
5994 if (eitherValidation.isRight()) {
5995 return eitherValidation;
5998 // validate template (derived from)
5999 log.debug("validate derived from");
6000 if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
6001 resource.setDerivedFrom(null);
6003 eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
6004 if (eitherValidation.isRight()) {
6005 return Either.right(eitherValidation.right().value());
6008 // warn about non-updatable fields
6009 checkComponentFieldsForOverrideAttempt(resource);
6010 String currentCreatorFullName = resource.getCreatorFullName();
6011 if (currentCreatorFullName != null) {
6012 log.warn("Resource Creator fullname is automatically set and cannot be updated");
6015 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
6016 if (currentLastUpdaterFullName != null) {
6017 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
6020 Long currentLastUpdateDate = resource.getLastUpdateDate();
6021 if (currentLastUpdateDate != null) {
6022 log.warn("Resource last update date is automatically set and cannot be updated");
6025 Boolean currentAbstract = resource.isAbstract();
6026 if (currentAbstract != null) {
6027 log.warn("Resource abstract is automatically set and cannot be updated");
6030 return Either.left(true);
6034 * validateResourceFieldsBeforeUpdate
6036 * @param currentResource - Resource object to validate
6037 * @return Either<Boolean, ErrorResponse>
6039 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
6041 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
6043 // validate resource name
6044 log.debug("validate resource name before update");
6045 Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified);
6046 if (eitherValidation.isRight()) {
6047 return eitherValidation;
6050 // validate description
6051 log.debug("validate description before update");
6052 eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
6053 if (eitherValidation.isRight()) {
6054 return eitherValidation;
6057 log.debug("validate icon before update");
6058 eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
6059 if (eitherValidation.isRight()) {
6060 return eitherValidation;
6063 log.debug("validate tags before update");
6064 eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
6065 if (eitherValidation.isRight()) {
6066 return eitherValidation;
6069 log.debug("validate vendor name before update");
6070 eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
6071 if (eitherValidation.isRight()) {
6072 return eitherValidation;
6075 log.debug("validate resource vendor model number before update");
6076 eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
6077 if (eitherValidation.isRight()) {
6078 return eitherValidation;
6082 log.debug("validate vendor release before update");
6083 eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
6084 if (eitherValidation.isRight()) {
6085 return eitherValidation;
6088 log.debug("validate contact info before update");
6089 eitherValidation = validateContactId(null, updateInfoResource, null);
6090 if (eitherValidation.isRight()) {
6091 return eitherValidation;
6094 log.debug("validate derived before update");
6095 eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
6096 if (eitherValidation.isRight()) {
6097 return eitherValidation;
6100 log.debug("validate category before update");
6101 eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
6102 if (eitherValidation.isRight()) {
6103 return eitherValidation;
6106 // warn about non-updatable fields
6107 String currentResourceVersion = currentResource.getVersion();
6108 String updatedResourceVersion = updateInfoResource.getVersion();
6110 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
6111 log.warn("Resource version is automatically set and cannot be updated");
6114 String currentCreatorUserId = currentResource.getCreatorUserId();
6115 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
6117 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
6118 log.warn("Resource Creator UserId is automatically set and cannot be updated");
6121 String currentCreatorFullName = currentResource.getCreatorFullName();
6122 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
6124 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
6125 log.warn("Resource Creator fullname is automatically set and cannot be updated");
6128 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
6129 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
6131 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
6132 log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
6135 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
6136 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
6138 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
6139 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
6142 Long currentCreationDate = currentResource.getCreationDate();
6143 Long updatedCreationDate = updateInfoResource.getCreationDate();
6145 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
6146 log.warn("Resource Creation date is automatically set and cannot be updated");
6149 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
6150 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
6152 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
6153 log.warn("Resource last update date is automatically set and cannot be updated");
6156 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
6157 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
6159 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
6160 log.warn("Resource lifecycle state date is automatically set and cannot be updated");
6163 Boolean currentAbstract = currentResource.isAbstract();
6164 Boolean updatedAbstract = updateInfoResource.isAbstract();
6166 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
6167 log.warn("Resource abstract is automatically set and cannot be updated");
6170 Boolean currentHighestVersion = currentResource.isHighestVersion();
6171 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
6173 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
6174 log.warn("Resource highest version is automatically set and cannot be updated");
6177 String currentUuid = currentResource.getUUID();
6178 String updatedUuid = updateInfoResource.getUUID();
6180 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
6181 log.warn("Resource UUID is automatically set and cannot be updated");
6184 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
6185 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
6187 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
6188 log.warn("Resource Type cannot be updated");
6191 updateInfoResource.setResourceType(currentResource.getResourceType());
6193 String currentInvariantUuid = currentResource.getInvariantUUID();
6194 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
6196 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
6197 log.warn("Resource invariant UUID is automatically set and cannot be updated");
6198 updateInfoResource.setInvariantUUID(currentInvariantUuid);
6200 return Either.left(true);
6204 * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName();
6206 * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
6207 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); }
6209 * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.
6210 * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat);
6213 * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME,
6214 * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName(
6215 * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ;
6217 * return Either.left(true); }
6219 private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
6220 String resourceNameUpdated = updateInfoResource.getName();
6221 String resourceNameCurrent = currentResource.getName();
6222 if (resourceNameCurrent.equals(resourceNameUpdated))
6224 // In case of CVFC type we should support the case of old VF with CVFC instances that were created without the "Cvfc" suffix
6225 return (currentResource.getResourceType().equals(ResourceTypeEnum.CVFC)
6226 && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)));
6229 private String addCvfcSuffixToResourceName(String resourceName) {
6230 return resourceName+"Cvfc";
6233 private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6234 String resourceNameUpdated = updateInfoResource.getName();
6235 if (!isResourceNameEquals(currentResource, updateInfoResource)) {
6236 if (!hasBeenCertified) {
6237 Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null);
6238 if (validateResourceNameResponse.isRight()) {
6239 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6240 return Either.right(errorResponse);
6242 validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
6243 if (validateResourceNameResponse.isRight()) {
6244 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6245 return Either.right(errorResponse);
6247 currentResource.setName(resourceNameUpdated);
6248 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
6249 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
6251 } else if(currentResource.getResourceType() != ResourceTypeEnum.CVFC) {
6252 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
6253 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
6254 return Either.right(errorResponse);
6257 return Either.left(true);
6260 private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6261 String iconUpdated = updateInfoResource.getIcon();
6262 String iconCurrent = currentResource.getIcon();
6263 if (!iconCurrent.equals(iconUpdated)) {
6264 if (!hasBeenCertified) {
6265 Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
6266 if (validateIcon.isRight()) {
6267 ResponseFormat errorResponse = validateIcon.right().value();
6268 return Either.right(errorResponse);
6271 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
6272 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
6273 return Either.right(errorResponse);
6276 return Either.left(true);
6279 private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6280 String vendorNameUpdated = updateInfoResource.getVendorName();
6281 String vendorNameCurrent = currentResource.getVendorName();
6282 if (!vendorNameCurrent.equals(vendorNameUpdated)) {
6283 if (!hasBeenCertified) {
6284 Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
6285 if (validateVendorName.isRight()) {
6286 ResponseFormat errorResponse = validateVendorName.right().value();
6287 return Either.right(errorResponse);
6290 log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated);
6291 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
6292 return Either.right(errorResponse);
6295 return Either.left(true);
6298 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
6299 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
6300 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
6301 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
6302 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null);
6303 if (validateResourceVendorModelNumber.isRight()) {
6304 ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
6305 return Either.right(errorResponse);
6308 return Either.left(true);
6311 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
6312 Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
6313 if (validateCategoryName.isRight()) {
6314 ResponseFormat errorResponse = validateCategoryName.right().value();
6315 return Either.right(errorResponse);
6317 if (hasBeenCertified) {
6318 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
6319 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
6320 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
6321 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
6322 if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
6323 log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
6324 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
6325 return Either.right(errorResponse);
6328 return Either.left(true);
6331 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6333 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
6334 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
6335 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
6336 log.trace("Update normative types");
6337 return Either.left(true);
6340 String derivedFromCurrent = currentDerivedFrom.get(0);
6341 String derivedFromUpdated = updatedDerivedFrom.get(0);
6343 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
6344 if (!hasBeenCertified) {
6345 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
6346 if (validateDerivedFromExistsEither.isRight()) {
6347 return validateDerivedFromExistsEither;
6350 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
6352 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
6353 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
6354 return validateDerivedFromExtending;
6358 // For derived from, we must know whether it was actually changed,
6359 // otherwise we must do no action.
6360 // Due to changes it inflicts on data model (remove artifacts,
6361 // properties...), it's not like a flat field which can be
6362 // overwritten if not changed.
6363 // So we must indicate that derived from is not changed
6364 updateInfoResource.setDerivedFrom(null);
6366 return Either.left(true);
6369 private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
6371 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
6372 return Either.left(true);
6375 // IResourceOperation resourceOperation = getResourceOperation();
6377 String templateName = resource.getDerivedFrom().get(0);
6379 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
6380 if (dataModelResponse.isRight()) {
6381 StorageOperationStatus storageStatus = dataModelResponse.right().value();
6382 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
6383 log.debug("request to data model failed with error: {}", storageStatus.name());
6384 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
6385 log.trace("audit before sending response");
6386 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6387 return Either.right(responseFormat);
6388 } else if (!dataModelResponse.left().value()) {
6389 log.info("resource template with name: {}, does not exists", templateName);
6390 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
6391 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6393 return Either.right(responseFormat);
6396 return Either.left(true);
6399 // Tal G for extending inheritance US815447
6400 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
6401 // If updated resource is not deriving, should fail validation
6403 * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6405 // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
6407 * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6409 String currentTemplateName = currentResource.getDerivedFrom().get(0);
6410 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
6412 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
6413 if (dataModelResponse.isRight()) {
6414 StorageOperationStatus storageStatus = dataModelResponse.right().value();
6415 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
6416 log.debug("request to data model failed with error: {}", storageStatus.name());
6417 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
6418 log.trace("audit before sending response");
6419 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6420 return Either.right(responseFormat);
6423 if (!dataModelResponse.left().value()) {
6424 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
6425 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
6426 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6428 return Either.right(responseFormat);
6431 return Either.left(true);
6434 public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
6435 log.debug("validate resource derivedFrom field");
6436 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
6437 log.info("derived from (template) field is missing for the resource");
6438 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
6439 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6441 return Either.right(responseFormat);
6443 return Either.left(true);
6446 private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
6448 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
6449 if (resourceOperationResponse.isLeft()) {
6450 if (!resourceOperationResponse.left().value()) {
6451 return Either.left(false);
6453 log.debug("resource with name: {}, already exists", resource.getName());
6454 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
6455 return Either.right(errorResponse);
6458 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
6459 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
6460 return Either.right(errorResponse);
6464 * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags();
6466 * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value();
6467 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true);
6471 * 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
6472 * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
6473 * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else {
6474 * 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");
6475 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize,
6476 * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); }
6478 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); }
6481 private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
6483 List<CategoryDefinition> categories = resource.getCategories();
6484 if (categories == null || categories.size() == 0) {
6485 log.debug("Resource category is empty");
6486 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6487 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6488 return Either.right(responseFormat);
6490 if (categories.size() > 1) {
6491 log.debug("Must be only one category for resource");
6492 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
6493 return Either.right(responseFormat);
6495 CategoryDefinition category = categories.get(0);
6496 List<SubCategoryDefinition> subcategories = category.getSubcategories();
6497 if (subcategories == null || subcategories.size() == 0) {
6498 log.debug("Missinig subcategory for resource");
6499 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
6500 return Either.right(responseFormat);
6502 if (subcategories.size() > 1) {
6503 log.debug("Must be only one sub category for resource");
6504 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
6505 return Either.right(responseFormat);
6508 SubCategoryDefinition subcategory = subcategories.get(0);
6510 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
6511 log.debug("Resource category is empty");
6512 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6513 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6514 return Either.right(responseFormat);
6516 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
6517 log.debug("Resource category is empty");
6518 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6519 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6520 return Either.right(responseFormat);
6523 Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
6524 if (validateCategory.isRight()) {
6525 ResponseFormat responseFormat = validateCategory.right().value();
6526 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6527 return Either.right(responseFormat);
6530 return Either.left(true);
6533 private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) {
6534 if (category != null && subcategory != null) {
6535 log.debug("validating resource category {} against valid categories list", category);
6536 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
6537 if (categories.isRight()) {
6538 log.debug("failed to retrive resource categories from Titan");
6539 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
6540 return Either.right(responseFormat);
6542 List<CategoryDefinition> categoryList = categories.left().value();
6543 for (CategoryDefinition cat : categoryList) {
6544 if (cat.getName().equals(category.getName())) {
6545 for (SubCategoryDefinition subcat : cat.getSubcategories()) {
6546 if (subcat.getName().equals(subcategory.getName())) {
6547 return Either.left(true);
6550 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories());
6551 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6554 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
6555 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6557 return Either.left(false);
6560 public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
6561 String vendorRelease = resource.getVendorRelease();
6563 log.debug("validate vendor relese name");
6564 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
6565 log.info("vendor relese name is missing.");
6566 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
6567 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6568 return Either.right(errorResponse);
6571 Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
6572 if (validateVendorReleaseResponse.isRight()) {
6573 ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
6574 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6576 return validateVendorReleaseResponse;
6579 public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
6580 if (vendorRelease != null) {
6581 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
6582 log.info("vendor release exceds limit.");
6583 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
6584 return Either.right(errorResponse);
6587 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
6588 log.info("vendor release is not valid.");
6589 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
6590 return Either.right(errorResponse);
6592 return Either.left(true);
6594 return Either.left(false);
6598 private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
6599 String vendorName = resource.getVendorName();
6600 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
6601 log.info("vendor name is missing.");
6602 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
6603 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6604 return Either.right(errorResponse);
6607 Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
6608 if (validateVendorNameResponse.isRight()) {
6609 ResponseFormat responseFormat = validateVendorNameResponse.right().value();
6610 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6612 return validateVendorNameResponse;
6616 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
6617 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
6618 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber);
6619 if (validateResourceVendorModelNumber.isRight()) {
6620 ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
6621 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6623 return validateResourceVendorModelNumber;
6628 private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
6629 if (vendorName != null) {
6630 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
6631 log.info("vendor name exceds limit.");
6632 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
6633 return Either.right(errorResponse);
6636 if (!ValidationUtils.validateVendorName(vendorName)) {
6637 log.info("vendor name is not valid.");
6638 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
6639 return Either.right(errorResponse);
6641 return Either.left(true);
6644 return Either.left(false);
6648 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
6649 if (resourceVendorModelNumber.equals("")) {
6650 return Either.left(true);
6652 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
6653 log.info("resource vendor model number exceeds limit.");
6654 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
6655 return Either.right(errorResponse);
6657 // resource vendor model number is currently validated as vendor name
6658 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
6659 log.info("resource vendor model number is not valid.");
6660 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
6661 return Either.right(errorResponse);
6663 return Either.left(true);
6669 * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
6670 * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
6671 * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6673 * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
6675 * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
6676 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
6678 * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
6679 * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
6681 * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
6682 * Either.left(false); }
6686 * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
6688 * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
6689 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6691 * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
6692 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
6694 * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
6695 * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6701 * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
6703 * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
6704 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6706 * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
6707 * null); } return validateIcon;
6711 * 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.
6712 * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
6713 * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6718 private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
6719 String cost = resource.getCost();
6722 if (!ValidationUtils.validateCost(cost)) {
6723 log.debug("resource cost is invalid.");
6724 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6725 return Either.right(errorResponse);
6728 return Either.left(true);
6731 private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
6732 log.debug("validate licenseType");
6733 String licenseType = resource.getLicenseType();
6734 if (licenseType != null) {
6735 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
6736 if (!licenseTypes.contains(licenseType)) {
6737 log.debug("License type {} isn't configured");
6738 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6739 if (actionEnum != null) {
6740 // In update case, no audit is required
6741 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6743 return Either.right(responseFormat);
6746 return Either.left(true);
6749 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
6750 Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
6751 if (updatedResource.getDerivedFrom() != null) {
6752 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
6753 log.debug("1. Removing interface artifacts from graph");
6754 // Remove all interface artifacts of resource
6755 String resourceId = updatedResource.getUniqueId();
6756 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
6758 if (interfaces != null) {
6759 Collection<InterfaceDefinition> values = interfaces.values();
6760 for (InterfaceDefinition interfaceDefinition : values) {
6761 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
6763 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
6764 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
6765 if (operations != null) {
6766 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
6767 Operation operation = operationEntry.getValue();
6768 ArtifactDefinition implementation = operation.getImplementationArtifact();
6769 if (implementation != null) {
6770 String uniqueId = implementation.getUniqueId();
6771 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
6772 // only thing that transacts and locks here
6773 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true);
6774 if (deleteArtifactByInterface.isRight()) {
6775 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
6776 if (!inTransaction) {
6777 titanDao.rollback();
6779 return Either.right(deleteArtifactByInterface.right().value());
6782 log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
6786 log.trace("No operations found for interface type {}", interfaceType);
6790 log.debug("2. Removing properties");
6791 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
6793 if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
6794 log.debug("Failed to remove all properties of resource");
6796 titanDao.rollback();
6797 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
6801 log.debug("Derived from wasn't changed during update");
6806 return Either.left(true);
6810 /**** Auditing *******************/
6812 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
6813 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
6815 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
6817 return webApplicationContext.getBean(class1);
6820 public ICapabilityTypeOperation getCapabilityTypeOperation() {
6821 return capabilityTypeOperation;
6824 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
6825 this.capabilityTypeOperation = capabilityTypeOperation;
6828 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
6829 log.debug("validate resource properties default values");
6830 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
6831 List<PropertyDefinition> properties = resource.getProperties();
6833 String innerType = null;
6834 if (properties != null) {
6835 for (PropertyDefinition property : properties) {
6836 if (!propertyOperation.isPropertyTypeValid(property)) {
6837 log.info("Invalid type for property");
6838 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
6839 eitherResult = Either.right(responseFormat);
6843 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
6844 if (allDataTypes.isRight()) {
6845 return Either.right(allDataTypes.right().value());
6848 type = property.getType();
6849 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6850 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value());
6851 innerType = propertyInnerTypeValid.getLeft();
6852 if (!propertyInnerTypeValid.getRight().booleanValue()) {
6853 log.info("Invalid inner type for property");
6854 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
6855 eitherResult = Either.right(responseFormat);
6860 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
6861 log.info("Invalid default value for property");
6862 ResponseFormat responseFormat;
6863 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6864 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
6866 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
6868 eitherResult = Either.right(responseFormat);
6874 return eitherResult;
6878 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
6879 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
6883 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
6884 return vfComponentInstanceBusinessLogic;
6887 private String getComponentTypeForResponse(Component component) {
6888 String componentTypeForResponse = "SERVICE";
6889 if (component instanceof Resource) {
6890 componentTypeForResponse = ((Resource) component).getResourceType().name();
6892 return componentTypeForResponse;
6895 private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6897 Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
6898 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
6900 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
6901 if (eitherNodesTemlates.isLeft()) {
6902 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
6904 if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
6905 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
6906 while (nodesNameValue.hasNext()) {
6907 Entry<String, Object> groupNameValue = nodesNameValue.next();
6909 String groupName = groupNameValue.getKey();
6910 Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue());
6911 if (eitherNode.isRight()) {
6912 String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName();
6913 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6914 return Either.right(eitherNode.right().value());
6916 GroupDefinition groupDefinition = eitherNode.left().value();
6917 groups.put(groupName, groupDefinition);
6926 private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6928 Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
6929 if (inputs.isRight()) {
6930 String message = "Failed when creating inputs: for resource:" + resource.getName();
6931 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6932 Map<String, InputDefinition> resultMap = new HashMap<>();
6933 return Either.left(resultMap);
6937 Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
6942 @SuppressWarnings("unchecked")
6943 private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
6945 GroupDefinition groupInfo = new GroupDefinition();
6946 groupInfo.setName(groupName);
6947 Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
6950 if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
6951 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
6952 String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
6953 if (!StringUtils.isEmpty(groupType)) {
6954 groupInfo.setType(groupType);
6956 log.debug("The 'type' member is not found under group {}", groupName);
6957 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
6960 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
6961 groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
6964 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
6965 Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
6966 if (members != null) {
6967 if (members instanceof List) {
6968 Map<String, String> membersLoaded = new HashMap<>();
6969 List<?> membersAsList = (List<?>) members;
6970 for (Object member : membersAsList) {
6971 membersLoaded.put(member.toString(), "");
6973 groupInfo.setMembers(membersLoaded);
6975 log.debug("The 'members' member is not of type list under group {}", groupName);
6976 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6981 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
6982 Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
6984 Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType);
6985 if (regResponse.isRight())
6986 return Either.right(regResponse.right().value());
6987 if (regResponse.left().value().size() > 0) {
6988 groupInfo.convertFromGroupProperties(regResponse.left().value());
6993 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6995 } catch (Exception e) {
6996 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
6997 log.debug("error when creating group, message:{}", e.getMessage(), e);
6998 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
7004 @SuppressWarnings("unchecked")
7005 private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) {
7007 List<GroupProperty> result = new ArrayList<>();
7009 if (properties == null) {
7010 return Either.left(result);
7013 Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
7015 if (groupTypeRes.isRight()) {
7016 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
7019 Map<String, PropertyDefinition> gtProperties = new HashMap<>();
7020 GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
7022 List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
7024 if (propertiesDef != null) {
7025 gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
7028 if (properties != null) {
7030 if (properties instanceof Map) {
7032 Map<String, Object> props = (Map<String, Object>) properties;
7033 for (Entry<String, Object> entry : props.entrySet()) {
7035 String propName = entry.getKey();
7036 Object value = entry.getValue();
7038 PropertyDefinition gtDefinition = gtProperties.get(propName);
7039 if (gtDefinition == null) {
7040 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType));
7043 ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
7045 String convertedValue = null;
7046 if (value != null) {
7047 if (type == null || value instanceof Map || value instanceof List) {
7048 convertedValue = gson.toJson(value);
7050 convertedValue = value.toString();
7054 GroupProperty groupProperty = new GroupProperty();
7055 groupProperty.setValue(convertedValue);
7056 groupProperty.setName(propName);
7058 log.trace("After building group property {}", groupProperty);
7060 result.add(groupProperty);
7067 return Either.left(result);
7070 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
7074 Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false);
7075 if (userValidation.isRight()) {
7076 return Either.right(userValidation.right().value());
7080 // get resource from csar uuid
7081 Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
7082 if (either.isRight()) {
7083 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
7084 return Either.right(resp);
7087 return Either.left(either.left().value());
7091 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
7095 private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
7096 ResponseFormat responseFormat;
7097 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
7099 for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
7100 String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
7101 if (!defaultCapabilities.containsKey(capabilityType)) {
7102 responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
7103 return Either.right(responseFormat);
7105 CapabilityDefinition defaultCapability;
7106 if(CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())){
7107 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
7109 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
7110 if(getFullComponentRes.isRight()){
7111 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
7112 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
7113 return Either.right(responseFormat);
7115 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
7117 if(CollectionUtils.isEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){
7118 log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
7119 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
7120 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
7121 return Either.right(responseFormat);
7123 if(CollectionUtils.isNotEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){
7124 Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
7125 if (validationRes.isRight()) {
7126 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value());
7127 return Either.right(responseFormat);
7130 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
7131 validCapabilityList.add(defaultCapability);
7132 validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
7135 return Either.left(validCapabilitiesMap);
7138 private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
7139 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
7140 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
7141 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
7142 for (UploadPropInfo property : uploadedProperties) {
7143 String propertyName = property.getName().toLowerCase();
7144 String propertyType = property.getType();
7145 ComponentInstanceProperty validProperty;
7146 if (defaultProperties.containsKey(propertyName)) {
7147 if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
7148 return Either.right(propertyName);
7151 validProperty = new ComponentInstanceProperty();
7152 validProperty.setName(propertyName);
7153 if (property.getValue() != null)
7154 validProperty.setValue(property.getValue().toString());
7155 validProperty.setDescription(property.getDescription());
7156 validProperty.setPassword(property.isPassword());
7157 validProperties.add(validProperty);
7159 defaultCapability.setProperties(validProperties);
7160 return Either.left(true);
7163 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
7164 Resource resource, User user) {
7166 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
7167 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
7168 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
7171 // add all found Csar artifacts to list to upload
7172 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
7173 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
7174 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
7175 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
7176 ArtifactDefinition foundArtifact;
7178 if (!existingArtifactsToHandle.isEmpty()) {
7179 foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
7180 if (foundArtifact != null) {
7181 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
7182 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
7183 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
7184 // if current artifact already exists, but has different content, add him to the list to update
7185 artifactsToUpdate.add(currNewArtifact);
7187 // remove found artifact from the list of existing artifacts to handle, because it was already handled
7188 existingArtifactsToHandle.remove(foundArtifact);
7189 // and remove found artifact from the list to upload, because it should either be updated or be ignored
7190 artifactsToUpload.remove(currNewArtifact);
7192 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
7193 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
7194 currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
7195 AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
7196 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
7197 responseWrapper.setInnerElement(responseFormat);
7203 if (responseWrapper.isEmpty()) {
7204 existingArtifactsToHandle.stream()
7205 // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
7206 .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
7208 if (responseWrapper.isEmpty()) {
7209 if (!artifactsToUpload.isEmpty())
7210 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
7211 if (!artifactsToUpdate.isEmpty())
7212 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
7213 if (!artifactsToDelete.isEmpty())
7214 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
7216 if (!responseWrapper.isEmpty()) {
7217 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
7219 } catch (Exception e) {
7220 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
7221 responseWrapper.setInnerElement(responseFormat);
7222 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
7224 return nodeTypeArtifactsToHandleRes;
7228 private String buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
7230 String actualVfName;
7231 if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){
7232 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
7233 actualType = ResourceTypeEnum.VFC.name();
7235 actualVfName = vfResourceName;
7236 actualType = nodeResourceType;
7238 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
7239 String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
7240 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
7241 String resourceType = findTypes[0];
7242 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
7244 if (actualName.startsWith(Constants.ABSTRACT)) {
7245 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
7247 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
7249 return toscaResourceName.append(actualName.toLowerCase()).toString();
7252 public ICacheMangerOperation getCacheManagerOperation() {
7253 return cacheManagerOperation;
7256 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
7257 this.cacheManagerOperation = cacheManagerOperation;
7260 ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
7262 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
7264 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
7265 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
7267 if (resourceResultEither.isRight()) {
7268 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
7269 log.debug("Failed to found resource with id {} ", resourceId);
7270 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
7273 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
7274 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
7277 Resource resource = resourceResultEither.left().value();
7278 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
7279 return Either.left(dataTransfer);