2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH;
24 import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.EnumMap;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Optional;
38 import java.util.function.Function;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import java.util.stream.Collectors;
43 import javax.servlet.ServletContext;
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.collections.CollectionUtils;
47 import org.apache.commons.collections.MapUtils;
48 import org.apache.commons.lang.StringUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
51 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
52 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
53 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
54 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
55 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
56 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
57 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
60 import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.api.ActionStatus;
63 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
64 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
65 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
66 import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
67 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
70 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
71 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
72 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
73 import org.openecomp.sdc.be.impl.ComponentsUtils;
74 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
75 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
76 import org.openecomp.sdc.be.info.MergedArtifactInfo;
77 import org.openecomp.sdc.be.model.ArtifactDefinition;
78 import org.openecomp.sdc.be.model.CapabilityDefinition;
79 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
80 import org.openecomp.sdc.be.model.Component;
81 import org.openecomp.sdc.be.model.ComponentInstance;
82 import org.openecomp.sdc.be.model.ComponentInstanceInput;
83 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
84 import org.openecomp.sdc.be.model.ComponentParametersView;
85 import org.openecomp.sdc.be.model.CsarInfo;
86 import org.openecomp.sdc.be.model.DataTypeDefinition;
87 import org.openecomp.sdc.be.model.GroupDefinition;
88 import org.openecomp.sdc.be.model.GroupProperty;
89 import org.openecomp.sdc.be.model.GroupTypeDefinition;
90 import org.openecomp.sdc.be.model.HeatParameterDefinition;
91 import org.openecomp.sdc.be.model.InputDefinition;
92 import org.openecomp.sdc.be.model.InterfaceDefinition;
93 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
94 import org.openecomp.sdc.be.model.LifecycleStateEnum;
95 import org.openecomp.sdc.be.model.NodeTypeInfo;
96 import org.openecomp.sdc.be.model.Operation;
97 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
98 import org.openecomp.sdc.be.model.PropertyDefinition;
99 import org.openecomp.sdc.be.model.RelationshipImpl;
100 import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
101 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
102 import org.openecomp.sdc.be.model.RequirementDefinition;
103 import org.openecomp.sdc.be.model.Resource;
104 import org.openecomp.sdc.be.model.UploadCapInfo;
105 import org.openecomp.sdc.be.model.UploadComponentInstanceInfo;
106 import org.openecomp.sdc.be.model.UploadPropInfo;
107 import org.openecomp.sdc.be.model.UploadReqInfo;
108 import org.openecomp.sdc.be.model.UploadResourceInfo;
109 import org.openecomp.sdc.be.model.User;
110 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
111 import org.openecomp.sdc.be.model.category.CategoryDefinition;
112 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
113 import org.openecomp.sdc.be.model.heat.HeatParameterType;
114 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
115 import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
116 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
117 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
118 import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
119 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
120 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
121 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
122 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
123 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
124 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
125 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
126 import org.openecomp.sdc.be.servlets.RepresentationUtils;
127 import org.openecomp.sdc.be.tosca.CsarUtils;
128 import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
129 import org.openecomp.sdc.be.tosca.ToscaUtils;
130 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
131 import org.openecomp.sdc.be.user.IUserBusinessLogic;
132 import org.openecomp.sdc.be.user.Role;
133 import org.openecomp.sdc.be.user.UserBusinessLogic;
134 import org.openecomp.sdc.be.utils.CommonBeUtils;
135 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
136 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
137 import org.openecomp.sdc.common.api.Constants;
138 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
139 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
140 import org.openecomp.sdc.common.datastructure.Wrapper;
141 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
142 import org.openecomp.sdc.common.util.GeneralUtility;
143 import org.openecomp.sdc.common.util.ValidationUtils;
144 import org.openecomp.sdc.exception.ResponseFormat;
145 import org.slf4j.Logger;
146 import org.slf4j.LoggerFactory;
147 import org.springframework.beans.factory.annotation.Autowired;
148 import org.springframework.web.context.WebApplicationContext;
149 import org.yaml.snakeyaml.DumperOptions;
150 import org.yaml.snakeyaml.Yaml;
151 import org.yaml.snakeyaml.parser.ParserException;
153 import com.google.gson.Gson;
154 import com.google.gson.JsonElement;
155 import com.google.gson.JsonObject;
157 import fj.data.Either;
159 @org.springframework.stereotype.Component("resourceBusinessLogic")
160 public class ResourceBusinessLogic extends ComponentBusinessLogic {
162 private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
163 public static final String INITIAL_VERSION = "0.1";
165 private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
166 private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
167 private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
168 private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
170 private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName());
172 private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
175 * Default constructor
177 public ResourceBusinessLogic() {
178 log.debug("ResourceBusinessLogic started");
182 private ICapabilityTypeOperation capabilityTypeOperation = null;
185 private IInterfaceLifecycleOperation interfaceTypeOperation = null;
188 private LifecycleBusinessLogic lifecycleBusinessLogic;
191 private IPropertyOperation propertyOperation;
194 private CsarOperation csarOperation;
197 private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic;
200 private ResourceImportManager resourceImportManager;
203 private GroupBusinessLogic groupBusinessLogic;
206 private InputsBusinessLogic inputsBusinessLogic;
209 private CompositionBusinessLogic compositionBusinessLogic;
212 private ICacheMangerOperation cacheManagerOperation;
215 private ApplicationDataTypeCache dataTypeCache;
217 private Gson gson = new Gson();
219 public CsarOperation getCsarOperation() {
220 return csarOperation;
223 public void setCsarOperation(CsarOperation csarOperation) {
224 this.csarOperation = csarOperation;
227 public LifecycleBusinessLogic getLifecycleBusinessLogic() {
228 return lifecycleBusinessLogic;
231 public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
232 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
235 public IElementOperation getElementDao() {
239 public void setElementDao(IElementOperation elementDao) {
240 this.elementDao = elementDao;
243 public IUserBusinessLogic getUserAdmin() {
244 return this.userAdmin;
247 public void setUserAdmin(UserBusinessLogic userAdmin) {
248 this.userAdmin = userAdmin;
251 public ComponentsUtils getComponentsUtils() {
252 return this.componentsUtils;
255 public void setComponentsUtils(ComponentsUtils componentsUtils) {
256 this.componentsUtils = componentsUtils;
259 public ArtifactsBusinessLogic getArtifactsManager() {
260 return artifactsBusinessLogic;
263 public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
264 this.artifactsBusinessLogic = artifactsManager;
267 public void setPropertyOperation(IPropertyOperation propertyOperation) {
268 this.propertyOperation = propertyOperation;
271 public ApplicationDataTypeCache getApplicationDataTypeCache() {
272 return applicationDataTypeCache;
275 public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
276 this.applicationDataTypeCache = applicationDataTypeCache;
280 * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param
286 public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
287 Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
288 if (resp.isRight()) {
289 return Either.right(resp.right().value());
291 Boolean isHighest = null;
292 switch (highestFilter) {
298 case NON_HIGHEST_ONLY:
304 Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
306 if (getResponse.isRight()) {
307 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
310 return Either.left(getResponse.left().value());
313 public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) {
315 Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
316 if (resp.isRight()) {
317 return Either.right(resp.right().value());
320 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
324 if (dataModelResponse.isLeft()) {
325 Map<String, Boolean> result = new HashMap<>();
326 result.put("isValid", dataModelResponse.left().value());
327 log.debug("validation was successfully performed.");
328 return Either.left(result);
331 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
333 return Either.right(responseFormat);
336 public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
337 Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
338 if (createResourceResponse.isRight()) {
339 return createResourceResponse;
342 // Creating resource either by DAO or from CSAR
343 String csarUUID = null;
344 if (payloadName == null) {
345 csarUUID = resource.getCsarUUID();
347 csarUUID = payloadName;
349 if (csarUUID != null && !csarUUID.isEmpty()) {
350 // check if VF with the same Csar UUID or with he same name already
352 Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
353 if (validateCsarUuidUniquenessRes.isRight()) {
354 log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
355 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
358 Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
359 if (existingResourceRes.intValue() > 0) {
360 log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
361 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID);
362 componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null);
363 return Either.right(errorResponse);
366 log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
367 createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
368 return createResourceResponse;
371 return createResourceByDao(resource, user, auditingAction, false, false, null);
374 public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
375 Either<Resource, ResponseFormat> updateResourceResponse = null;
376 Either<Resource, ResponseFormat> validateResourceResponse = null;
377 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
378 String csarUUID = null;
379 String csarVersion = null;
380 if (payloadName == null) {
381 csarUUID = resource.getCsarUUID();
382 csarVersion = resource.getCsarVersion();
384 csarUUID = payloadName;
386 if (csarUUID != null && !csarUUID.isEmpty()) {
387 Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
388 if (responseWrapper.isEmpty()) {
389 validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
391 if (responseWrapper.isEmpty()) {
392 validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
394 if (responseWrapper.isEmpty()) {
395 if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
396 overrideImmutableMetadata(oldResource, resource);
398 validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
399 if (validateResourceResponse.isRight()) {
400 responseWrapper.setInnerElement(validateResourceResponse.right().value());
403 if (responseWrapper.isEmpty()) {
404 String oldCsarVersion = oldResource.getCsarVersion();
405 log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId);
406 // (on boarding flow): If the update includes same csarUUID and
407 // same csarVersion as already in the VF - no need to import the
408 // csar (do only metadata changes if there are).
409 if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
410 updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
412 updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
416 log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
417 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName());
418 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
419 responseWrapper.setInnerElement(errorResponse);
421 if (responseWrapper.isEmpty()) {
422 return updateResourceResponse;
424 return Either.right(responseWrapper.getInnerElement());
427 private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource, Resource resource, String csarUUID, User user) {
428 // (on boarding flow): If the update includes a csarUUID: verify this
429 // csarUUID is not in use by another VF, If it is - use same error as
431 // "Error: The VSP with UUID %1 was already imported for VF %2. Please
432 // select another or update the existing VF." %1 - csarUUID, %2 - VF
434 Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
435 if (resourceLinkedToCsarRes.isRight()) {
436 if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
437 log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
438 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
440 } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
441 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
442 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
443 responseWrapper.setInnerElement(errorResponse);
447 private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
448 // (on boarding flow): If the update includes csarUUID which is
449 // different from the csarUUID of the VF - fail with
450 // error: "Error: Resource %1 cannot be updated using since it is linked
451 // to a different VSP" %1 - VF name
452 String oldCsarUUID = oldResource.getCsarUUID();
453 if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
454 log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", resourceUniqueId, csarUUID, oldCsarUUID);
455 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
456 componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
457 responseWrapper.setInnerElement(errorResponse);
461 private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
462 Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId);
463 if (oldResourceRes.isRight()) {
464 log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
465 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
468 return oldResourceRes.left().value();
471 private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
472 resource.setName(oldRresource.getName());
473 resource.setIcon(oldRresource.getIcon());
474 resource.setTags(oldRresource.getTags());
475 resource.setVendorName(oldRresource.getVendorName());
476 resource.setCategories(oldRresource.getCategories());
477 resource.setDerivedFrom(oldRresource.getDerivedFrom());
480 private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload,
484 if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
485 if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
486 log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", oldRresource.getLastUpdaterUserId(), user.getUserId());
487 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
490 String lockedResourceId = oldRresource.getUniqueId();
491 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
493 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
494 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
495 csar = csarUIPayload;
497 csar = csarOperation.getCsar(csarUUID, user);
499 if (csar.isRight()) {
500 log.debug("Failed to get csar for casrUUID{} ", csarUUID);
501 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
504 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, user, csarUUID, csar);
505 if (toscaYamlCsarStatus.isRight()) {
506 return Either.right(toscaYamlCsarStatus.right().value());
508 Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
509 if (checksum.isRight()) {
510 log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
511 return Either.right(checksum.right().value());
513 boolean isUpdateYaml = true;
514 if (checksum.left().value().equals(oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
515 log.debug("The checksums are equals for csarUUID {}, existing checsum is {}, new one is {} ", csarUUID, oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum.left().value());
516 if (oldRresource.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT))
517 isUpdateYaml = false;
519 oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum.left().value());
522 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource, "update Resource From Csar");
523 if (lockResult.isRight()) {
524 return Either.right(lockResult.right().value());
527 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
528 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
529 CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, true);
530 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
531 Either<Resource, ResponseFormat> result = null;
533 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, oldRresource);
534 if (findNodeTypesArtifactsToHandleRes.isRight()) {
535 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
536 result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
539 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value();
541 result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, isUpdateYaml, yamlFileName, yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null);
544 if (result == null || result.isRight()) {
545 log.warn("operation failed. do rollback");
547 if (!createdArtifacts.isEmpty()) {
548 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
549 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
550 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
551 result = Either.right(componentsUtils.getResponseFormat(actionStatus, oldRresource.getName()));
553 log.debug("component and all its artifacts were deleted, id = {}", oldRresource.getName());
556 log.debug("operation success. do commit");
559 log.debug("unlock resource {}", lockedResourceId);
560 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
566 private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts,
567 boolean isUpdateYaml, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
568 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, String nodeName) {
569 Either<Resource, ResponseFormat> result;
570 Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither;
571 boolean inTransaction = true;
572 boolean shouldLock = false;
574 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate;
575 Resource preparedResource;
576 Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName);
577 if (uploadComponentInstanceInfoMap.isRight()) {
578 ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
579 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, "", "", updateResource, null);
580 result = Either.right(responseFormat);
584 Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances();
586 if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) {
588 prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock);
589 if (prepareForUpdate.isRight()) {
590 log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
591 result = Either.right(prepareForUpdate.right().value());
594 preparedResource = prepareForUpdate.left().value().left;
596 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
598 parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
599 if (parseNodeTypeInfoYamlEither.isRight()) {
600 ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
601 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
602 result = Either.right(responseFormat);
606 Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
607 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource, csarInfo.getModifier(), inputs, inTransaction);
608 if (createInputsOnResource.isRight()) {
609 log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
610 ResponseFormat responseFormat = createInputsOnResource.right().value();
611 componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
612 result = Either.right(responseFormat);
615 preparedResource = createInputsOnResource.left().value();
617 Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock, csarInfo.getCreatedNodes());
618 if (createResourcesInstancesEither.isRight()) {
619 log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
620 ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
621 componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
622 result = Either.right(responseFormat);
625 preparedResource = createResourcesInstancesEither.left().value();
627 createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
628 if (createResourcesInstancesEither.isRight()) {
629 log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
630 result = Either.right(createResourcesInstancesEither.right().value());
634 preparedResource = createResourcesInstancesEither.left().value();
636 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), preparedResource.getSystemName());
637 if (validateUpdateVfGroupNamesRes.isRight()) {
639 return Either.right(validateUpdateVfGroupNamesRes.right().value());
641 // add groups to resource
642 Map<String, GroupDefinition> groups;
644 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
645 groups = validateUpdateVfGroupNamesRes.left().value();
647 groups = uploadComponentInstanceInfoMap.left().value().getGroups();
649 Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource, csarInfo.getModifier(), groups);
650 if (updatedGroupsOnResource.isRight()) {
652 return updatedGroupsOnResource;
654 preparedResource = updatedGroupsOnResource.left().value();
657 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(oldRresource.getUniqueId(), newRresource, csarInfo.getModifier(), oldRresource, shouldLock, inTransaction);
658 if (dataModelResponse.isRight()) {
659 log.debug("failed to update resource metadata {}", dataModelResponse.right().value());
660 result = Either.right(dataModelResponse.right().value());
663 preparedResource = dataModelResponse.left().value();
666 if(preparedResource.getResourceType() == ResourceTypeEnum.CVFC){
667 if(nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()){
668 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
669 handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
670 if(handleNodeTypeArtifactsRes.isRight()){
671 return Either.right(handleNodeTypeArtifactsRes.right().value());
675 Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
676 artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), shouldLock, inTransaction);
677 log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
678 if (createdCsarArtifactsEither.isRight()) {
679 return createdCsarArtifactsEither;
681 preparedResource = createdCsarArtifactsEither.left().value();
684 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
685 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource);
690 private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
692 Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
693 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
694 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
697 nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
698 Map<String, String> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
699 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes;
700 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
701 log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarInfo.getCsarUUID());
703 for (Entry<String, String> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) {
704 String currVfcToscaName = currVfcToscaNameEntry.getValue();
705 String currNamespace = currVfcToscaNameEntry.getKey();
706 log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
708 Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
709 Resource curNodeType = null;
710 if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
711 log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value());
712 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarInfo.getCsarUUID());
713 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
714 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
716 } else if (curVfcRes.isLeft()) {
717 curNodeType = curVfcRes.left().value();
719 if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
720 List<ArtifactDefinition> currArtifacts = new ArrayList<>();
721 if (extractedVfcsArtifacts.containsKey(currNamespace)) {
722 handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
724 curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
725 if (curNodeTypeArtifactsToHandleRes.isRight()) {
726 nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
729 curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
731 } else if (curNodeType != null) {
732 // delete all artifacts if have not received artifacts from csar
733 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
734 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
735 // delete all informational artifacts
736 artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList()));
737 // delete all deployment artifacts
738 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
739 if (!artifactsToDelete.isEmpty()) {
740 curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
743 if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
744 nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
747 } catch (Exception e) {
748 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
749 nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
750 log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
752 return nodeTypesArtifactsToHandleRes;
755 private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
757 Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
758 EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
759 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
761 List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
762 List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
763 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
764 if (curNodeType != null) {
765 Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
766 if (curNodeType.getDeploymentArtifacts() != null) {
767 existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
769 if (curNodeType.getArtifacts() != null) {
770 existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
772 for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
773 ArtifactDefinition foundArtifact;
775 if (!existingArtifacts.isEmpty()) {
776 foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
777 if (foundArtifact != null) {
778 if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
779 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
780 foundArtifact.setPayload(currNewArtifact.getPayloadData());
781 foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
782 foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
783 artifactsToUpdate.add(foundArtifact);
785 existingArtifacts.remove(foundArtifact.getArtifactLabel());
786 artifactsToUpload.remove(currNewArtifact);
788 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
789 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
790 foundArtifact.getArtifactType());
791 responseWrapper.setInnerElement(responseFormat);
797 if (responseWrapper.isEmpty()) {
798 artifactsToDelete.addAll(existingArtifacts.values());
801 if (responseWrapper.isEmpty()) {
802 if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
803 nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
804 if (!artifactsToUpload.isEmpty())
805 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
806 if (!artifactsToUpdate.isEmpty())
807 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
808 if (!artifactsToDelete.isEmpty())
809 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
811 nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
813 if (!responseWrapper.isEmpty()) {
814 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
816 } catch (Exception e) {
817 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
818 responseWrapper.setInnerElement(responseFormat);
819 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
821 return nodeTypeArtifactsToHandleRes;
825 * Changes resource life cycle state to checked out
829 * @param inTransaction
832 private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
833 Either<Resource, ResponseFormat> checkoutResourceRes;
835 if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
836 log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
837 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
838 new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
839 if (checkoutRes.isRight()) {
840 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
841 checkoutResourceRes = Either.right(checkoutRes.right().value());
843 checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
846 checkoutResourceRes = Either.left(resource);
848 } catch (Exception e) {
849 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
850 checkoutResourceRes = Either.right(responseFormat);
851 log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
853 return checkoutResourceRes;
857 * Handles Artifacts of NodeType
859 * @param nodeTypeResource
860 * @param nodeTypeArtifactsToHandle
861 * @param vfcsNewCreatedArtifacts
863 * @param inTransaction
866 public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> createdArtifacts,
867 User user, boolean inTransaction, boolean ignoreLifecycleState) {
868 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
869 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
870 Either<Resource, ResponseFormat> changeStateResponse;
872 changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
873 if (changeStateResponse.isRight()) {
874 return Either.right(changeStateResponse.right().value());
876 nodeTypeResource = changeStateResponse.left().value();
878 List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
879 log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
880 for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
881 ArtifactOperationEnum curOperation = curOperationEntry.getKey();
882 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
883 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
884 log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
885 handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
886 artifactsBusinessLogic.new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
887 if (handleNodeTypeArtifactsRequestRes.isRight()) {
888 handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
891 if (curOperation == ArtifactOperationEnum.Create) {
892 createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
894 handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
897 if (handleNodeTypeArtifactsRes == null) {
898 handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
900 } catch (Exception e) {
901 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
902 handleNodeTypeArtifactsRes = Either.right(responseFormat);
903 log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
905 return handleNodeTypeArtifactsRes;
908 private Map<String, String> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName, CsarInfo csarInfo) {
909 Map<String, String> vfcToscaNames = new HashMap<>();
911 Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
912 if (!nodes.isEmpty()) {
913 Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
914 while (nodesNameEntry.hasNext()) {
915 Entry<String, Object> nodeType = nodesNameEntry.next();
916 String toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
917 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
920 return vfcToscaNames;
923 private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
924 Map<String, Object> nodes = new HashMap<>();
925 for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){
926 extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
928 extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
932 private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
933 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
934 if (eitherNodeTypes.isLeft()) {
935 nodes.putAll(eitherNodeTypes.left().value());
939 public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
940 log.trace("************* created successfully from YAML, resource TOSCA ");
942 Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
943 if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
944 csar = csarUIPayload;
946 csar = csarOperation.getCsar(csarUUID, user);
949 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar);
950 if (toscaYamlCsarStatus.isRight()) {
951 return Either.right(toscaYamlCsarStatus.right().value());
953 Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
954 if (toscaYamlChecksum.isRight()) {
955 log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, toscaYamlChecksum.right().value());
956 return Either.right(toscaYamlChecksum.right().value());
958 resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value());
960 String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
961 String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
962 log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
964 CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, false);
965 Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
966 Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, resource);
967 if (findNodeTypesArtifactsToHandleRes.isRight()) {
968 log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
969 return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
971 Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
972 if (createResourceFromYaml.isRight()) {
973 log.debug("Couldn't create resource from YAML");
974 return Either.right(createResourceFromYaml.right().value());
977 Resource vfResource = createResourceFromYaml.left().value();
978 log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
979 return Either.left(vfResource);
982 private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) {
983 Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
984 List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
985 for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) {
986 extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry);
988 if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
989 setDerivedFrom(nodeTypesInfo, globalSubstitutes);
991 markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo);
992 return nodeTypesInfo;
995 @SuppressWarnings("unchecked")
996 private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo, List<Entry<String, byte[]>> globalSubstitutes) {
997 for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
998 String yamlFileContents = new String(entry.getValue());
999 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1000 Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
1001 if (nodeTypesEither.isLeft()) {
1002 Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
1003 for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
1004 Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
1005 if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
1006 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1007 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
1008 List<String> derivedFrom = new ArrayList<>();
1009 derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
1010 nodeTypeInfo.setDerivedFrom(derivedFrom);
1018 @SuppressWarnings("unchecked")
1019 private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
1020 List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) {
1021 if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
1022 if (!isGlobalSubstitute(entry.getKey())) {
1023 String yamlFileContents = new String(entry.getValue());
1024 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
1025 Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
1026 if (substitutionMappingsEither.isLeft()) {
1027 Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value();
1028 if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
1029 NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
1030 nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
1031 nodeTypeInfo.setTemplateFileName(entry.getKey());
1032 nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
1033 nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
1037 globalSubstitutes.add(entry);
1043 @SuppressWarnings("unchecked")
1044 private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
1045 Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
1046 if (nodeTemplatesEither.isLeft()) {
1047 Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
1048 for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
1049 Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
1050 if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
1051 String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
1052 if (nodeTypesInfo.containsKey(type)) {
1053 NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
1054 nodeTypeInfo.setNested(true);
1061 private boolean isGlobalSubstitute(String fileName) {
1062 return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
1065 private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
1066 if (csar.isRight()) {
1067 StorageOperationStatus value = csar.right().value();
1068 log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
1069 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1070 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
1071 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1072 return Either.right(responseFormat);
1075 Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils);
1076 if (validateCsarStatus.isRight()) {
1077 ResponseFormat responseFormat = validateCsarStatus.right().value();
1078 log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
1079 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1080 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1081 return Either.right(responseFormat);
1084 Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
1086 if (toscaYamlCsarStatus.isRight()) {
1087 ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
1088 log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
1089 BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
1090 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
1091 return Either.right(responseFormat);
1093 return toscaYamlCsarStatus;
1096 private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
1097 log.trace("validating resource before create");
1098 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false);
1099 if (eitherCreator.isRight()) {
1100 return Either.right(eitherCreator.right().value());
1102 user.copyData(eitherCreator.left().value());
1104 // validate user role
1105 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
1106 if (validateRes.isRight()) {
1107 return Either.right(validateRes.right().value());
1109 // VF / PNF "derivedFrom" should be null (or ignored)
1110 if (ToscaUtils.isAtomicType(resource)) {
1111 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
1112 if (validateDerivedFromNotEmpty.isRight()) {
1113 return Either.right(validateDerivedFromNotEmpty.right().value());
1116 return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
1119 //resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, nodeTypesArtifactsToCreate, true, false, null
1120 private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
1121 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
1122 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1123 boolean shouldLock, boolean inTransaction, String nodeName) {
1125 List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
1126 log.trace("************* createResourceFromYaml before parse yaml ");
1127 Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName);
1128 if (parseResourceInfoFromYamlEither.isRight()) {
1129 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
1130 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1131 return Either.right(responseFormat);
1133 log.trace("************* createResourceFromYaml after parse yaml ");
1134 ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
1135 log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
1136 log.trace("************* createResourceFromYaml before create ");
1137 Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
1138 AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
1139 nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
1140 log.trace("************* createResourceFromYaml after create ");
1141 if (createdResourceResponse.isRight()) {
1142 ResponseFormat responseFormat = createdResourceResponse.right().value();
1143 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1144 return Either.right(responseFormat);
1147 return createdResourceResponse;
1151 public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
1152 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1153 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
1155 Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
1156 if (tosca_version.isRight()) {
1157 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
1158 return Either.right(responseFormat);
1160 Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
1161 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
1162 Map<String, Object> mapToConvert = new HashMap<String, Object>();
1163 mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
1164 Resource vfcCreated = null;
1165 if (eitherNodeTypes.isLeft()) {
1166 Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
1167 while (nodesNameValue.hasNext()) {
1168 Entry<String, Object> nodeType = nodesNameValue.next();
1169 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
1171 if (nodeTypesInfo.containsKey(nodeType.getKey())) {
1172 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
1173 Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey());
1174 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
1175 if (handleNeatedVfcYaml.isRight()) {
1176 return Either.right(handleNeatedVfcYaml.right().value());
1178 vfcCreated = handleNeatedVfcYaml.left().value();
1179 } else if(csarInfo.getCreatedNodesToscaResourceNames()!= null && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){
1180 log.trace("************* Going to create node {}", nodeType.getKey());
1181 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo);
1182 log.debug("************* Finished to create node {}", nodeType.getKey());
1184 if (resourceCreated.isRight()) {
1185 return Either.right(resourceCreated.right().value());
1187 vfcCreated = resourceCreated.left().value().getLeft();
1188 csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName());
1190 if (vfcCreated != null) {
1191 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
1193 mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
1199 private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
1200 List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName) {
1202 Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
1203 String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
1204 Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
1206 log.debug("************* Going to create node types from yaml {}", yamlName);
1207 Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(yamlName, resource,
1208 nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
1209 if (createNodeTypesRes.isRight()) {
1210 log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, createNodeTypesRes.right().value());
1211 return Either.right(createNodeTypesRes.right().value());
1213 log.debug("************* Finished to create node types from yaml {}", yamlName);
1215 if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
1216 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
1217 handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
1219 return handleNestedVfcRes;
1222 private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts,
1223 Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
1225 Either<Resource, ResponseFormat> result = null;
1226 Resource oldComplexVfc = null;
1227 Resource newComplexVfc = null;
1229 Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
1230 if(buildCvfcRes.isRight()){
1231 log.debug("Failed to validate complex VFC for node {}. ", nodeName);
1232 result = buildCvfcRes;
1235 newComplexVfc = buildCvfcRes.left().value();
1236 Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade.getLatestByToscaResourceName(newComplexVfc.getToscaResourceName());
1237 if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){
1238 log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
1239 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1240 } else if(oldComplexVfcRes.isLeft()){
1241 oldComplexVfc = oldComplexVfcRes.left().value();
1245 result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, newComplexVfc);
1247 if(result.isLeft()){
1248 newComplexVfc = result.left().value();
1249 csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
1250 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1251 log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
1252 result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
1253 if (result.isRight()) {
1254 log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
1257 if(result.isLeft()){
1258 csarInfo.getCreatedNodes().put(nodeName, result.left().value());
1259 csarInfo.getCvfcToCreateQueue().remove();
1264 private Either<Resource, ResponseFormat> handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo,
1265 CsarInfo csarInfo, String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
1267 Either<Resource, ResponseFormat> handleComplexVfcRes;
1268 Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
1269 String yamlContent = new String(csarInfo.getCsar().get(yamlName));
1270 Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
1271 markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
1272 if(oldComplexVfc == null){
1273 handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, false, true, nodeName);
1274 if (handleComplexVfcRes.isRight()) {
1275 log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName);
1278 handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName);
1279 if (handleComplexVfcRes.isRight()) {
1280 log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName);
1283 return handleComplexVfcRes;
1286 private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1288 Either<Resource, ResponseFormat> result = null;
1289 Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
1290 log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
1292 if(!csarInfo.getCvfcToCreateQueue().contains(nodeName)){
1293 csarInfo.getCvfcToCreateQueue().add(nodeName);
1295 log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), csarInfo.getVfResourceName());
1296 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, csarInfo.getVfResourceName(), complexVfc.getName()));
1299 result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
1300 if(result.isRight()){
1301 log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
1307 private String getNodeTypeActualName(String fullName) {
1308 String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1309 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1310 String resourceType = findTypes[0];
1311 return nameWithouNamespacePrefix.substring(resourceType.length());
1314 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
1315 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) {
1317 Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
1318 if (resourceMetaData.isRight()) {
1319 return Either.right(resourceMetaData.right().value());
1321 String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo.getVfResourceName());
1323 Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
1324 if (eitherCreator.isRight()) {
1325 return Either.right(eitherCreator.right().value());
1327 user = eitherCreator.left().value();
1329 return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo);
1332 private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, String csarVfName) {
1333 // We need to create a Yaml from each node_types in order to create
1334 // resource from each node type using import normative flow.
1335 DumperOptions options = new DumperOptions();
1336 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
1337 Yaml yaml = new Yaml(options);
1339 Map<String, Object> node = new HashMap<>();
1340 node.put(buildNestedToscaResourceName(nodeResourceType, csarVfName, nodeNameValue.getKey()), nodeNameValue.getValue());
1341 mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
1343 return yaml.dumpAsMap(mapToConvert);
1346 public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
1348 Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
1349 if (validateDerivedFromNotEmpty.isRight()) {
1350 return Either.right(validateDerivedFromNotEmpty.right().value());
1352 return Either.left(true);
1355 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
1356 Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo) {
1358 LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
1359 Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
1360 return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo);
1363 private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
1364 UploadResourceInfo resourceMetaData = new UploadResourceInfo();
1366 // validate nodetype name prefix
1367 if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
1368 log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
1369 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1370 return Either.right(responseFormat);
1373 String actualName = this.getNodeTypeActualName(nodeName);
1374 String namePrefix = nodeName.replace(actualName, "");
1375 String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1377 // if we import from csar, the node_type name can be
1378 // org.openecomp.resource.abstract.node_name - in this case we always
1380 if (resourceType.equals(Constants.ABSTRACT)) {
1381 resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
1384 if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
1385 log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
1386 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
1387 return Either.right(responseFormat);
1391 resourceMetaData.setName(resourceVf.getSystemName() + actualName);
1393 // Setting type from name
1394 String type = resourceType.toUpperCase();
1395 resourceMetaData.setResourceType(type);
1397 resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
1398 resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1399 resourceMetaData.setContactId(user.getUserId());
1400 resourceMetaData.setVendorName(resourceVf.getVendorName());
1401 resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
1404 List<String> tags = new ArrayList<>();
1405 tags.add(resourceMetaData.getName());
1406 resourceMetaData.setTags(tags);
1409 CategoryDefinition category = new CategoryDefinition();
1410 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1411 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1412 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1413 category.addSubCategory(subCategory);
1414 List<CategoryDefinition> categories = new ArrayList<>();
1415 categories.add(category);
1416 resourceMetaData.setCategories(categories);
1418 return Either.left(resourceMetaData);
1421 private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
1422 Resource cvfc = new Resource();
1423 NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
1424 cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
1425 cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
1426 cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
1427 cvfc.setResourceType(ResourceTypeEnum.CVFC);
1428 cvfc.setAbstract(true);
1429 cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
1430 cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
1431 cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
1432 cvfc.setContactId(csarInfo.getModifier().getUserId());
1433 cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
1434 cvfc.setVendorName(resourceVf.getVendorName());
1435 cvfc.setVendorRelease(resourceVf.getVendorRelease());
1436 cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
1437 cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName));
1438 cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
1440 List<String> tags = new ArrayList<>();
1441 tags.add(cvfc.getName());
1444 CategoryDefinition category = new CategoryDefinition();
1445 category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
1446 SubCategoryDefinition subCategory = new SubCategoryDefinition();
1447 subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
1448 category.addSubCategory(subCategory);
1449 List<CategoryDefinition> categories = new ArrayList<>();
1450 categories.add(category);
1451 cvfc.setCategories(categories);
1453 cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
1454 cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
1455 cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
1460 private String buildCvfcName(String resourceVfName, String nodeName) {
1461 String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
1462 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
1463 String resourceType = findTypes[0];
1464 return resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1) + "Cvfc";
1467 private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
1468 List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo,
1469 CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1470 boolean shouldLock, boolean inTransaction, String nodeName) {
1472 boolean result = true;
1473 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
1476 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
1477 if (lockResult.isRight()) {
1478 ResponseFormat responseFormat = lockResult.right().value();
1479 return Either.right(responseFormat);
1481 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
1484 log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
1485 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
1486 if (genericResourceEither.isRight()) {
1488 return genericResourceEither;
1490 Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, csarInfo.getModifier(), isNormative, inTransaction);
1491 log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
1492 if (createResourcesEither.isRight()) {
1494 return createResourcesEither;
1496 resource = createResourcesEither.left().value();
1497 // add groups to resource
1498 log.trace("************* Going to add inputs from yaml {}", yamlName);
1499 if (resource.shouldGenerateInputs())
1500 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
1502 Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
1503 Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, csarInfo.getModifier(), inputs, inTransaction);
1504 if (createInputsOnResource.isRight()) {
1506 return createInputsOnResource;
1508 resource = createInputsOnResource.left().value();
1509 log.trace("************* Finish to add inputs from yaml {}", yamlName);
1511 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
1512 log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
1514 createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml,
1515 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
1516 log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
1517 if (createResourcesEither.isRight()) {
1519 return createResourcesEither;
1522 resource = createResourcesEither.left().value();
1523 // validate update vf module group names
1524 Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
1525 if (validateUpdateVfGroupNamesRes.isRight()) {
1527 return Either.right(validateUpdateVfGroupNamesRes.right().value());
1529 // add groups to resource
1530 Map<String, GroupDefinition> groups;
1531 log.trace("************* Going to add groups from yaml {}", yamlName);
1533 if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
1534 groups = validateUpdateVfGroupNamesRes.left().value();
1536 groups = parsedToscaYamlInfo.getGroups();
1538 Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, csarInfo.getModifier(), groups);
1539 if (createGroupsOnResource.isRight()) {
1541 return createGroupsOnResource;
1543 resource = createGroupsOnResource.left().value();
1544 log.trace("************* Finished to add groups from yaml {}", yamlName);
1546 log.trace("************* Going to add artifacts from yaml {}", yamlName);
1548 if(resource.getResourceType() == ResourceTypeEnum.CVFC){
1549 if(nodeTypesArtifactsToCreate.containsKey(nodeName) && nodeTypesArtifactsToCreate.get(nodeName) !=null && !nodeTypesArtifactsToCreate.get(nodeName).isEmpty()){
1550 Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
1551 handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeName), nodeTypesNewCreatedArtifacts, csarInfo.getModifier(), true, false);
1552 if(handleNodeTypeArtifactsRes.isRight()){
1553 return Either.right(handleNodeTypeArtifactsRes.right().value());
1557 Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, csarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
1559 log.trace("************* Finished to add artifacts from yaml {}", yamlName);
1560 if (createdCsarArtifactsEither.isRight()) {
1562 return createdCsarArtifactsEither;
1564 resource = createdCsarArtifactsEither.left().value();
1566 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
1567 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", actionEnum, null);
1568 ASDCKpiApi.countCreatedResourcesKPI();
1569 return Either.left(resource);
1572 if (!inTransaction) {
1574 log.warn("operation failed. do rollback");
1575 titanDao.rollback();
1576 if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
1577 createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
1578 StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
1579 if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
1580 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
1581 return Either.right(componentsUtils.getResponseFormat(actionStatus, resource.getName()));
1583 log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
1587 log.debug("operation success. do commit");
1592 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
1597 private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1598 if (groups != null && !groups.isEmpty()) {
1599 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1601 if (mergeGroupsUsingResource.isRight()) {
1602 log.debug("Failed to prepare groups for creation");
1603 return Either.right(mergeGroupsUsingResource.right().value());
1605 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1606 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList);
1607 if (createGroups.isRight()) {
1608 return Either.right(createGroups.right().value());
1611 return Either.left(resource);
1613 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1614 if (updatedResource.isRight()) {
1615 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1616 return Either.right(responseFormat);
1618 return Either.left(updatedResource.left().value());
1621 private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
1622 if (groups != null && false == groups.isEmpty()) {
1623 List<GroupDefinition> groupsFromResource = resource.getGroups();
1624 Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
1626 if (mergeGroupsUsingResource.isRight()) {
1627 log.debug("Failed to prepare groups for creation");
1628 return Either.right(mergeGroupsUsingResource.right().value());
1630 List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
1631 List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
1632 List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
1633 List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
1634 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1635 for (GroupDefinition group : groupsAsList) {
1636 Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1637 if (op.isPresent()) {
1638 GroupDefinition groupToUpdate = op.get();
1639 groupToUpdate.setMembers(group.getMembers());
1640 groupsToUpdate.add(groupToUpdate);
1642 groupsToCreate.add(group);
1645 for (GroupDefinition group : groupsFromResource) {
1646 Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
1647 if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
1649 groupsToDelete.add(group);
1654 groupsToCreate.addAll(groupsAsList);
1655 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
1656 if (!groupsToCreate.isEmpty()) {
1658 if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
1659 prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1661 prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
1664 if (prepareGroups.isRight()) {
1665 return Either.right(prepareGroups.right().value());
1669 if (!groupsToDelete.isEmpty()) {
1670 prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
1671 if (prepareGroups.isRight()) {
1672 return Either.right(prepareGroups.right().value());
1676 if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
1677 prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
1678 if (prepareGroups.isRight()) {
1679 return Either.right(prepareGroups.right().value());
1684 return Either.left(resource);
1687 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1688 if (updatedResource.isRight()) {
1689 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1690 return Either.right(responseFormat);
1692 return Either.left(updatedResource.left().value());
1695 private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
1696 List<InputDefinition> resourceProperties = resource.getInputs();
1697 if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) {
1699 Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
1700 if (createInputs.isRight()) {
1701 return Either.right(createInputs.right().value());
1704 return Either.left(resource);
1707 Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
1708 if (updatedResource.isRight()) {
1709 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
1710 return Either.right(responseFormat);
1712 return Either.left(updatedResource.left().value());
1715 private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
1717 List<GroupDefinition> result = new ArrayList<>();
1719 List<ComponentInstance> componentInstances = component.getComponentInstances();
1721 if (groups != null) {
1722 Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
1723 if (validateCyclicGroupsDependencies.isRight()) {
1724 return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
1726 for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
1727 String groupName = entry.getKey();
1729 GroupDefinition groupDefinition = entry.getValue();
1731 GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
1732 updatedGroupDefinition.setMembers(null);
1734 // get the members of the group
1735 Map<String, String> members = groupDefinition.getMembers();
1736 if (members != null) {
1737 Set<String> compInstancesNames = members.keySet();
1739 if (componentInstances == null || true == componentInstances.isEmpty()) {
1740 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1741 log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName());
1742 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1744 // Find all component instances with the member names
1745 Map<String, String> memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
1746 memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
1747 Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
1749 if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
1751 List<String> foundMembers = new ArrayList<>();
1752 if (relevantInstances != null) {
1753 foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
1755 compInstancesNames.removeAll(foundMembers);
1756 String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
1757 log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
1758 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
1761 updatedGroupDefinition.setMembers(relevantInstances);
1764 result.add(updatedGroupDefinition);
1767 return Either.left(result);
1771 * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
1776 private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
1778 Either<Boolean, ResponseFormat> result = Either.left(true);
1780 Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
1781 while (allGroupsItr.hasNext() && result.isLeft()) {
1782 Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
1783 // Fetches a group member A
1784 String groupAName = groupAEntry.getKey();
1785 // Finds all group members in group A
1786 Set<String> allGroupAMembersNames = new HashSet<>();
1787 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
1788 // If A is a group member of itself found cyclic dependency
1789 if (allGroupAMembersNames.contains(groupAName)) {
1790 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
1791 result = Either.right(responseFormat);
1794 } catch (Exception e) {
1795 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1796 result = Either.right(responseFormat);
1797 log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
1803 * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
1807 * @param allGroupMembers
1810 private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1812 // Found Cyclic dependency
1813 if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
1816 GroupDefinition groupDefinition = allGroups.get(groupName);
1817 // All Members Of Current Group Resource Instances & Other Groups
1818 Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
1819 // Filtered Members Of Current Group containing only members which
1821 List<String> currGroupFilteredMembers = currGroupMembers.stream().
1822 // Keep Only Elements of type group and not Resource Instances
1823 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1824 // Add Filtered Elements to main Set
1825 peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
1827 collect(Collectors.toList());
1829 // Recursively call the method for all the filtered group members
1830 for (String innerGroupName : currGroupFilteredMembers) {
1831 fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
1836 private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
1838 boolean stop = false;
1839 // In Case Not Group Stop
1840 if (!allGroups.containsKey(groupName)) {
1843 // In Case Group Has no members stop
1845 GroupDefinition groupDefinition = allGroups.get(groupName);
1846 stop = MapUtils.isEmpty(groupDefinition.getMembers());
1849 // In Case all group members already contained stop
1851 final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
1852 Set<String> membersOfTypeGroup = allMembers.stream().
1853 // Filter In Only Group members
1854 filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
1856 collect(Collectors.toSet());
1857 stop = allGroupMembers.containsAll(membersOfTypeGroup);
1862 private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
1863 String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1864 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
1867 Either<Resource, ResponseFormat> result;
1868 Either<Resource, ResponseFormat> createResourcesInstancesEither;
1870 log.debug("************* Going to create all nodes {}", yamlName);
1871 Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
1872 if (createdResourcesFromdNodeTypeMap.isRight()) {
1873 log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
1874 return Either.right(createdResourcesFromdNodeTypeMap.right().value());
1876 log.debug("************* Finished to create all nodes {}", yamlName);
1878 log.debug("************* Going to create all resource instances {}", yamlName);
1879 createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes());
1881 if (createResourcesInstancesEither.isRight()) {
1882 log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
1883 result = createResourcesInstancesEither;
1884 return createResourcesInstancesEither;
1886 log.debug("************* Finished to create all resource instances for {}", yamlName);
1887 resource = createResourcesInstancesEither.left().value();
1888 log.debug("************* Going to create all relations {}", yamlName);
1889 createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
1891 if (createResourcesInstancesEither.isRight()) {
1892 log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
1893 result = createResourcesInstancesEither;
1896 resource = createResourcesInstancesEither.left().value();
1898 log.debug("************* Finished to create all relations {}", yamlName);
1900 log.debug("************* Going to create positions {}", yamlName);
1901 Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
1902 log.debug("************* Finished to set positions {}", yamlName);
1903 result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
1908 private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
1909 List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
1910 artifactsToAdd.stream().forEach(a -> {
1911 if (!vfcArtifactNames.contains(a.getArtifactName())) {
1912 vfcArtifacts.add(a);
1914 log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
1920 @SuppressWarnings("unchecked")
1921 private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
1922 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
1923 Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, String nodeName) {
1925 Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
1926 for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
1927 if (nodeTypeEntry.getValue().isNested()) {
1929 Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle,
1930 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
1931 log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
1932 if (createResourceFromYaml.isRight()) {
1933 return Either.right(createResourceFromYaml.right().value());
1938 Map<String, Object> mappedToscaTemplate = null;
1939 if(StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)){
1940 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
1942 if(MapUtils.isEmpty(mappedToscaTemplate)){
1943 mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
1946 Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
1947 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
1948 if (createdNodeTypeFromMainTemplateEither.isRight()) {
1949 ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
1950 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
1951 return Either.right(responseFormat);
1954 // add the created node types to the cache although they are not in the
1956 csarInfo.getCreatedNodes().values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
1961 private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
1962 boolean inTransaction) {
1964 if (csarInfo.getCsar() != null) {
1965 String vendorLicenseModelId = null;
1966 String vfLicenseModelId = null;
1968 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
1969 Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
1970 if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
1971 for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
1972 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
1973 vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
1974 if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
1975 vfLicenseModelId = artifactEntry.getValue().getUniqueId();
1980 // Specific Behavior for license artifacts
1981 createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1982 Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1983 createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
1984 Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
1986 Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
1987 if (eitherCreateResult.isRight()) {
1988 return Either.right(eitherCreateResult.right().value());
1991 Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
1992 if (artifacsMetaCsarStatus.isLeft()) {
1994 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
1995 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
1996 Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
1997 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
1998 createArtifactsFromCsar = createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2000 createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
2001 if (createArtifactsFromCsar.isRight()) {
2002 log.debug("Couldn't create artifacts from artifacts.meta");
2003 return Either.right(createArtifactsFromCsar.right().value());
2006 resource = createArtifactsFromCsar.left().value();
2008 List<GroupDefinition> groupsToDelete = resource.getGroups();
2010 if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
2011 Set<String> artifactsToDelete = new HashSet<String>();
2013 * for (GroupDefinition group : groupsToDelete) { List<String> artifacts = group.getArtifacts(); if (artifacts != null) { artifactsToDelete.addAll(artifacts); Either<GroupDefinition, StorageOperationStatus> deleteGroupEither =
2014 * groupOperation.deleteGroup(group.getUniqueId(), inTransaction); if (deleteGroupEither.isRight()) { StorageOperationStatus storageOperationStatus = deleteGroupEither.right().value(); ActionStatus actionStatus =
2015 * componentsUtils.convertFromStorageResponse(storageOperationStatus); log.debug("Failed to delete group {} under component {}, error: {}", group.getUniqueId(), resource.getNormalizedName(), actionStatus.name()); return
2016 * Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
2018 for (String artifactId : artifactsToDelete) {
2019 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
2020 resource, null, null, shouldLock, inTransaction);
2021 if (handleDelete.isRight()) {
2022 log.debug("Couldn't delete artifact {}", artifactId);
2023 return Either.right(handleDelete.right().value());
2026 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2027 if (eitherGetResource.isRight()) {
2028 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
2030 return Either.right(responseFormat);
2033 resource = eitherGetResource.left().value();
2037 return Either.left(resource);
2040 private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath, String artifactFileName, String artifactType,
2041 ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
2042 boolean inTransaction) {
2043 byte[] artifactFileBytes = null;
2045 if (csarInfo.getCsar().containsKey(artifactPath)) {
2046 artifactFileBytes = csarInfo.getCsar().get(artifactPath);
2048 Either<Boolean, ResponseFormat> result = Either.left(true);
2049 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
2050 if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
2051 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
2052 null, shouldLock, inTransaction);
2053 if (handleDelete.isRight()) {
2054 result = Either.right(handleDelete.right().value());
2059 if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
2060 operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
2064 if (artifactFileBytes != null) {
2065 Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
2066 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction);
2067 addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
2068 if (eitherNonMetaArtifacts.isRight()) {
2069 BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
2070 return Either.right(eitherNonMetaArtifacts.right().value());
2076 private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
2077 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
2078 Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
2079 if (eitherResult.isLeft()) {
2080 createdArtifacts.add(eitherResult.left().value());
2085 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) {
2087 String jsonStr = gson.toJson(json);
2089 String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr);
2090 ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
2091 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
2092 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId,
2093 artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true, false);
2094 if (uploadArtifactToService.isRight())
2095 return Either.right(uploadArtifactToService.right().value());
2097 return Either.left(uploadArtifactToService.left().value());
2100 public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
2101 boolean shouldLock, boolean inTransaction) {
2103 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
2104 if (parseResourceInfoFromYamlEither.isRight()) {
2105 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2106 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2107 return Either.right(responseFormat);
2110 List<GroupDefinition> groups = resource.getGroups();
2111 Map<String, ArtifactDefinition> deplymentArtifact = resource.getDeploymentArtifacts();
2112 List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = new ArrayList<ArtifactDefinition>();
2113 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2114 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2115 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2118 int labelCounter = createdDeplymentArtifactsAfterDelete.size();
2120 if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
2121 if (groups != null && !groups.isEmpty()) {
2122 for (GroupDefinition group : groups) {
2123 if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) {
2124 log.debug("failed to update artifacts from csar. List of emty but group not empty");
2125 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2126 return Either.right(responseFormat);
2130 return createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
2133 // find master in group
2134 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
2136 ////////////////////////////////////// create set parsed
2137 ////////////////////////////////////// artifacts///////////////////////////////////////////
2138 Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
2139 Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
2140 Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>();
2142 for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
2143 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2144 parsedGroupTemplate.setGroupName("");
2145 Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<ArtifactTemplateInfo>();
2146 parsedArtifactsNames.add(parsedGroupTemplate);
2147 List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
2148 if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
2149 createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
2151 parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
2155 ///////////////////////////////// find artifacts to
2156 ///////////////////////////////// delete////////////////////////////////////////////////////
2158 Set<ArtifactDefinition> artifactsToDelete = new HashSet<ArtifactDefinition>();
2159 Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<String, List<ArtifactDefinition>>();
2161 Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
2162 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
2164 // Set<String> deletedArtifactsName = new HashSet<String>();
2165 Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete);
2166 if (deletedArtifactsEither.isRight()) {
2167 log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
2169 return Either.right(deletedArtifactsEither.right().value());
2172 List<ArtifactDefinition> deletedArtifacts = deletedArtifactsEither.left().value();
2174 // need to update resource if we updated artifacts
2175 if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) {
2176 for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
2177 ArtifactDefinition artToRemove = null;
2178 for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
2179 if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
2180 artToRemove = artFromResource;
2184 if (artToRemove != null)
2185 createdDeplymentArtifactsAfterDelete.remove(artToRemove);
2190 ////////////// dissociate, associate or create
2191 ////////////// artifacts////////////////////////////
2192 Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
2193 mergedgroup, deletedArtifacts);
2195 if (assDissotiateEither.isRight()) {
2196 log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
2198 return Either.right(assDissotiateEither.right().value());
2201 resource = assDissotiateEither.left().value();
2202 deplymentArtifact = resource.getDeploymentArtifacts();
2203 createdDeplymentArtifactsAfterDelete.clear();
2204 if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
2205 for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
2206 createdDeplymentArtifactsAfterDelete.add(entry.getValue());
2210 groups = resource.getGroups();
2212 // update vfModule names
2213 Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
2214 if (groups != null && !groups.isEmpty()) {
2215 Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
2216 if (validateUpdateVfGroupNamesRes.isRight()) {
2217 return Either.right(validateUpdateVfGroupNamesRes.right().value());
2219 List<GroupDefinition> heatGroups = null;
2221 heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2224 for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
2226 if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
2227 updatedGroupDef.getMembers().clear();
2229 Map<String, String> members = new HashMap<String, String>();
2230 Set<String> artifactsGroup = new HashSet<String>();
2231 artifactsGroup.addAll(updatedGroupDef.getArtifacts());
2232 associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
2233 if (!members.isEmpty()) {
2234 updatedGroupDef.setMembers(members);
2244 //////////////// create new artifacts in update
2245 //////////////// flow////////////////////////////
2246 List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<ArtifactTemplateInfo>();
2248 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2249 ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
2250 boolean isNewGroup = true;
2251 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2252 Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
2253 Set<ArtifactDefinition> group = groupArtifacts.keySet();
2254 for (ArtifactDefinition artifactInfo : group) {
2255 if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
2256 parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
2262 newArtifactsGroup.add(parsedArtifactMaster);
2265 if (!newArtifactsGroup.isEmpty()) {
2266 Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
2267 int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
2268 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter);
2269 if (validateGroupNamesRes.isRight()) {
2270 return Either.right(validateGroupNamesRes.right().value());
2272 Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
2273 if (resStatus.isRight())
2278 if (!groupForAssociateWithMembers.isEmpty()) {
2280 List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
2282 Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId);
2283 if (updateVersionEither.isRight()) {
2284 log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
2286 return Either.right(updateVersionEither.right().value());
2291 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2292 if (eitherGerResource.isRight()) {
2293 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2295 return Either.right(responseFormat);
2298 return Either.left(eitherGerResource.left().value());
2302 private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
2303 Map<String, List<ArtifactDefinition>> groupToDelete) {
2304 List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
2305 String resourceId = resource.getUniqueId();
2306 if (!artifactsToDelete.isEmpty()) {
2307 for (ArtifactDefinition artifact : artifactsToDelete) {
2308 String artifactType = artifact.getArtifactType();
2309 ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
2310 if (artifactTypeEnum == ArtifactTypeEnum.HEAT_ENV) {
2313 * Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromGraph = artifactOperation.removeArifactFromResource(resourceId, artifact.getUniqueId(), NodeTypeEnum.Resource, true, true); if
2314 * (removeArifactFromGraph.isRight()) { StorageOperationStatus status = removeArifactFromGraph.right().value(); log.debug("Failed to delete heat env artifact {} . status is {}", artifact.getUniqueId(), status); ActionStatus
2315 * actionStatus = componentsUtils.convertFromStorageResponse(status); return Either.right(componentsUtils.getResponseFormat(actionStatus)); }
2317 * deletedArtifacts.add(removeArifactFromGraph.left().value());
2321 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
2322 null, null, shouldLock, inTransaction);
2323 if (handleDelete.isRight()) {
2324 return Either.right(handleDelete.right().value());
2327 deletedArtifacts.add(handleDelete.left().value().left().value());
2332 if (!groupToDelete.isEmpty()) {
2333 log.debug("try to delete group");
2334 List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
2335 List<GroupDefinition> groups = resource.getGroups();
2336 for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
2337 Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
2338 if (op.isPresent()) {
2339 groupDefinitionstoDelete.add(op.get());
2343 if (!groupDefinitionstoDelete.isEmpty()) {
2344 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete);
2345 if (prepareGroups.isRight()) {
2346 return Either.right(prepareGroups.right().value());
2350 return Either.left(deletedArtifacts);
2353 private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
2354 boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
2355 Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
2356 Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
2357 Either<Resource, ResponseFormat> resEither = Either.left(resource);
2358 for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
2359 List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts);
2360 GroupDefinition grDef = entry.getKey();
2361 if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
2362 for (ArtifactDefinition art : dissArtifactsInGroup) {
2363 grDef.getArtifacts().remove(art.getUniqueId());
2364 grDef.getArtifactsUuid().remove(art.getArtifactUUID());
2368 List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
2369 if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
2370 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
2372 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
2373 if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
2374 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
2377 if (!artifactsToUpdateMap.isEmpty()) {
2378 List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>();
2379 for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
2380 List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
2381 GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
2383 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
2384 String prevUUID = artifact.getKey().getArtifactUUID();
2385 String prevId = artifact.getKey().getUniqueId();
2386 Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
2387 artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
2388 if (updateArtifactEither.isRight()) {
2389 log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
2390 resEither = Either.right(updateArtifactEither.right().value());
2393 ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
2394 if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
2395 groupToUpdate.getArtifacts().remove(prevId);
2396 groupToUpdate.getArtifactsUuid().remove(prevUUID);
2397 groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
2398 groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
2404 for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
2405 List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
2406 Set<String> arifactsUids = new HashSet<String>();
2407 Set<String> arifactsUuids = new HashSet<String>();
2408 for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
2414 boolean isCreate = true;
2415 for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
2416 if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
2417 arifactsUids.add(createdArtifact.getUniqueId());
2418 arifactsUuids.add(createdArtifact.getArtifactUUID());
2420 String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
2421 if (!heatEnvId.isEmpty()) {
2422 arifactsUids.add(heatEnvId);
2423 Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
2424 if (op.isPresent()) {
2425 this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
2434 if (isCreate) { // check if already created
2435 for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
2436 if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
2437 arifactsUids.add(createdNewArtifact.getUniqueId());
2438 arifactsUuids.add(createdNewArtifact.getArtifactUUID());
2440 String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
2441 if (!heatEnvId.isEmpty()) {
2442 arifactsUids.add(heatEnvId);
2450 Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
2451 if (createArtifactEither.isRight()) {
2452 resEither = Either.right(createArtifactEither.right().value());
2455 ArtifactDefinition createdArtifact = createArtifactEither.left().value();
2456 arifactsUids.add(createdArtifact.getUniqueId());
2457 arifactsUuids.add(createdArtifact.getArtifactUUID());
2458 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
2459 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2460 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2461 resource.getName(), csarInfo.getModifier(), resource, null);
2462 if (createHeatEnvPlaceHolder.isRight()) {
2463 return Either.right(createHeatEnvPlaceHolder.right().value());
2465 String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
2466 arifactsUids.add(heatEnvId);
2471 if (arifactsUids.size() > 0) {
2472 List<String> artifactsToAssociate = new ArrayList<String>();
2473 artifactsToAssociate.addAll(arifactsUids);
2474 GroupDefinition assotiateGroup = associateEntry.getKey();
2475 assotiateGroup.getArtifacts().addAll(arifactsUids);
2476 assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
2481 * if (!associateArtifactGroup.isEmpty()) {
2483 * log.debug("Try to associate artifacts to groups.");
2485 * Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateArtifactsToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, associateArtifactGroup, shouldLock, inTransaction); if
2486 * (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); resEither = Either.right(assotiateGroupEither.right().value()); return resEither;
2491 ComponentParametersView parametersView = new ComponentParametersView();
2492 parametersView.disableAll();
2493 parametersView.setIgnoreComponentInstances(false);
2494 parametersView.setIgnoreUsers(false);
2495 parametersView.setIgnoreArtifacts(false);
2496 parametersView.setIgnoreGroups(false);
2498 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
2500 if (eitherGerResource.isRight()) {
2501 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2503 resEither = Either.right(responseFormat);
2507 resEither = Either.left(eitherGerResource.left().value());
2511 private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
2512 Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
2513 Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
2514 for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
2515 Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
2516 boolean isNeedToDeleteGroup = true;
2517 List<ArtifactDefinition> listToDelete = null;
2518 for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
2519 listToDelete = createdArtifactMap.get(maserArtifact);
2520 for (ArtifactDefinition artToDelete : listToDelete) {
2521 findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
2523 if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
2524 GroupDefinition group = groupListEntry.getKey();
2525 for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
2526 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
2527 group.getArtifacts().remove(artifactDefinition.getUniqueId());
2530 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
2531 group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
2538 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
2539 if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
2540 MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
2541 mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
2542 mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
2543 mergedgroup.put(groupListEntry.getKey(), mergedGroup);
2544 isNeedToDeleteGroup = false;
2550 if (isNeedToDeleteGroup) {
2551 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
2558 private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
2559 List<ArtifactDefinition> createdDeplymentArtifacts) {
2560 boolean isNeedToDeleteArtifact = true;
2561 String artifactType = artifact.getArtifactType();
2562 ArtifactDefinition generatedFromArt = null;
2563 if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
2564 Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
2566 generatedFromArt = op.get();
2570 for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
2571 Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
2572 for (ArtifactTemplateInfo template : artifactsNames) {
2573 if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
2574 isNeedToDeleteArtifact = false;
2578 if (generatedFromArt != null) {
2579 if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
2580 isNeedToDeleteArtifact = false;
2588 if (isNeedToDeleteArtifact) {
2589 artifactsToDelete.add(artifact);
2594 private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
2595 Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>();
2597 for (GroupDefinition group : groups) {
2598 Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>();
2599 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
2600 List<String> artifactsList = group.getArtifacts();
2601 if (artifactsList != null && !artifactsList.isEmpty()) {
2603 ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList);
2604 if (masterArtifact != null)
2605 gupsMap.put(masterArtifact, artifacts);
2606 groupArtifact.put(group, gupsMap);
2610 return groupArtifact;
2613 private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
2615 for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
2616 parsedArtifactsName.add(parsedGroupTemplate);
2617 List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
2618 if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
2619 createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
2624 public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
2625 boolean shouldLock, boolean inTransaction) {
2627 log.debug("parseResourceArtifactsInfoFromFile start");
2628 Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
2629 if (parseResourceInfoFromYamlEither.isRight()) {
2630 ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
2631 componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
2632 return Either.right(responseFormat);
2634 log.debug("parseResourceArtifactsInfoFromFile end");
2636 log.debug("createResourceArtifacts start");
2637 Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
2638 if (respStatus.isRight()) {
2641 log.debug("createResourceArtifacts end");
2642 log.debug("getResource start");
2643 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
2644 log.debug("getResource end");
2645 if (eitherGerResource.isRight()) {
2646 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
2648 return Either.right(responseFormat);
2651 return Either.left(eitherGerResource.left().value());
2655 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
2656 List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
2657 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2658 List<GroupDefinition> createdGroups = resource.getGroups();
2659 List<GroupDefinition> heatGroups = null;
2660 if (createdGroups != null && !createdGroups.isEmpty()) {
2661 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2664 List<GroupDefinition> needToAdd = new ArrayList<>();
2665 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2666 String groupName = groupTemplateInfo.getGroupName();
2667 Set<String> artifactsGroup = new HashSet<String>();
2668 Set<String> artifactsUUIDGroup = new HashSet<String>();
2670 resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
2671 if (resStatus.isRight())
2674 Map<String, String> members = new HashMap<String, String>();
2675 associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
2677 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2678 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2680 GroupDefinition groupDefinition = new GroupDefinition();
2681 groupDefinition.setName(groupName);
2682 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
2683 groupDefinition.setArtifacts(artifactsList);
2684 groupDefinition.setArtifactsUuid(artifactsUUIDList);
2686 if (!members.isEmpty())
2687 groupDefinition.setMembers(members);
2689 List<GroupProperty> properties = new ArrayList<GroupProperty>();
2690 GroupProperty prop = new GroupProperty();
2691 prop.setName(Constants.IS_BASE);
2692 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
2693 properties.add(prop);
2695 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
2696 createdArtifacts.addAll(createdNewArtifacts);
2697 createdArtifacts.addAll(artifactsFromResource);
2698 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
2699 if (getLatestGroupTypeRes.isRight()) {
2700 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
2702 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
2703 groupDefinition.convertFromGroupProperties(properties);
2705 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
2706 // if (createGroup.isRight())
2707 // return Either.right(createGroup.right().value());
2708 needToAdd.add(groupDefinition);
2710 ComponentParametersView componentParametersView = new ComponentParametersView();
2711 componentParametersView.disableAll();
2712 componentParametersView.setIgnoreArtifacts(false);
2713 componentParametersView.setIgnoreGroups(false);
2714 componentParametersView.setIgnoreComponentInstances(false);
2716 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
2717 if (component.isRight()) {
2718 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2720 resource = component.left().value();
2722 Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd);
2723 if (addGroups.isRight())
2724 return Either.right(addGroups.right().value());
2729 private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
2730 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
2731 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2732 String artifactFileName = artifactTemplateInfo.getFileName();
2733 String artifactUid = "";
2734 String artifactUUID = "";
2735 String artifactEnvUid = "";
2736 boolean alreadyExist = false;
2738 // check if artifacts already exist
2739 if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
2740 for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
2741 if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
2742 artifactUid = artifactFromResource.getUniqueId();
2743 artifactUUID = artifactFromResource.getArtifactUUID();
2744 if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2745 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
2746 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2747 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
2749 alreadyExist = true;
2750 artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
2757 if (!alreadyExist) {
2758 for (ArtifactDefinition createdArtifact : createdArtifacts) {
2759 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
2760 artifactUid = createdArtifact.getUniqueId();
2761 artifactUUID = createdArtifact.getArtifactUUID();
2763 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
2764 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
2765 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
2766 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
2768 alreadyExist = true;
2769 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
2775 // if not exist need to create
2776 if (!alreadyExist) {
2778 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
2779 if (newArtifactEither.isRight()) {
2780 resStatus = Either.right(newArtifactEither.right().value());
2783 ArtifactDefinition newArtifact = newArtifactEither.left().value();
2784 artifactUid = newArtifact.getUniqueId();
2785 artifactUUID = newArtifact.getArtifactUUID();
2786 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
2787 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
2788 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
2789 resource.getName(), csarInfo.getModifier(), resource, null);
2790 if (createHeatEnvPlaceHolder.isRight()) {
2791 return Either.right(createHeatEnvPlaceHolder.right().value());
2793 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
2797 artifactsGroup.add(artifactUid);
2798 artifactsUUIDGroup.add(artifactUUID);
2799 if (!artifactEnvUid.isEmpty()) {
2800 artifactsGroup.add(artifactEnvUid);
2803 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
2804 if (relatedArtifacts != null) {
2805 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
2806 resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
2807 if (resStatus.isRight())
2814 private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
2815 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
2817 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2819 Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
2821 for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
2822 if (groupTemplateList != null) {
2823 resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
2824 if (resStatus.isRight())
2833 private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) {
2835 Either<Resource, ResponseFormat> resStatus = null;
2836 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
2839 List<NonMetaArtifactInfo> artifactPathAndNameList =
2840 // Stream of file paths contained in csar
2841 csarInfo.getCsar().entrySet().stream()
2842 // Filter in only VF artifact path location
2843 .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
2844 // Validate and add warnings
2845 .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
2846 // Filter in Non Warnings
2847 .filter(e -> e.isLeft())
2848 // Convert from Either to NonMetaArtifactInfo
2849 .map(e -> e.left().value())
2851 .collect(Collectors.toList());
2853 Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
2854 if (responseFormatEither.isRight()) {
2855 return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
2859 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
2861 if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
2862 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
2863 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
2865 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, csarInfo.getModifier());
2867 if (findVfCsarArtifactsToHandleRes.isRight()) {
2868 resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
2870 if (resStatus == null) {
2871 vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
2874 if (resStatus == null && vfCsarArtifactsToHandle != null) {
2875 for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
2877 Optional<ResponseFormat> optionalCreateInDBError =
2878 // Stream of artifacts to be created
2879 currArtifactOperationPair.getValue().stream()
2880 // create each artifact
2881 .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
2882 CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
2884 // filter in only error
2885 .filter(e -> e.isRight()).
2886 // Convert the error from either to ResponseFormat
2887 map(e -> e.right().value()).
2888 // Check if an error occurred
2890 // Error found on artifact Creation
2891 if (optionalCreateInDBError.isPresent()) {
2892 resStatus = Either.right(optionalCreateInDBError.get());
2897 if (resStatus == null) {
2898 resStatus = Either.left(resource);
2900 } catch (Exception e) {
2901 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2902 log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
2904 CsarUtils.handleWarningMessages(collectedWarningMessages);
2909 private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
2910 Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
2911 for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
2912 if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
2913 return Either.right(nonMetaArtifactInfo.getArtifactName());
2916 return Either.left(true);
2920 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
2922 List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
2923 // collect all Deployment and Informational artifacts of VF
2924 if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
2925 existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
2927 if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
2928 existingArtifacts.addAll(resource.getArtifacts().values());
2930 existingArtifacts = existingArtifacts.stream()
2931 // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
2932 .filter(this::isNonMetaArtifact).collect(Collectors.toList());
2934 List<String> artifactsToIgnore = new ArrayList<>();
2935 // collect IDs of Artifacts of VF which belongs to any group
2936 if (resource.getGroups() != null) {
2937 resource.getGroups().stream().forEach(g -> {
2938 if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
2939 artifactsToIgnore.addAll(g.getArtifacts());
2942 existingArtifacts = existingArtifacts.stream()
2943 // filter artifacts which belongs to any group
2944 .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
2945 return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
2948 private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
2949 boolean result = true;
2950 if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
2956 private boolean isValidArtifactType(ArtifactDefinition artifact) {
2957 boolean result = true;
2958 if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
2964 private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
2965 int labelCounter, boolean shouldLock, boolean inTransaction) {
2966 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
2967 List<GroupDefinition> createdGroups = resource.getGroups();
2968 List<GroupDefinition> heatGroups = null;
2969 if (createdGroups != null && !createdGroups.isEmpty()) {
2971 // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
2972 // e.getArtifacts().stream()).filter(p ->
2973 // relevantArtifactTypes.contains(p.getArtifactType()
2974 // )).collect(Collectors.toList());
2975 // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
2976 // e -> e.getProperties().stream().filter(p ->
2977 // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
2978 heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
2981 List<GroupDefinition> needToCreate = new ArrayList<>();
2982 for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
2983 String groupName = groupTemplateInfo.getGroupName();
2984 Set<String> artifactsGroup = new HashSet<String>();
2985 Set<String> artifactsUUIDGroup = new HashSet<String>();
2987 log.debug("createDeploymentArtifactsFromCsar start");
2988 resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
2989 log.debug("createDeploymentArtifactsFromCsar end");
2990 if (resStatus.isRight())
2993 Map<String, String> members = new HashMap<String, String>();
2994 associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
2996 List<String> artifactsList = new ArrayList<String>(artifactsGroup);
2997 List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
2999 GroupDefinition groupDefinition = new GroupDefinition();
3000 groupDefinition.setName(groupName);
3001 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
3002 groupDefinition.setArtifacts(artifactsList);
3003 groupDefinition.setArtifactsUuid(artifactsUUIDList);
3005 if (!members.isEmpty())
3006 groupDefinition.setMembers(members);
3007 List<GroupProperty> properties = new ArrayList<GroupProperty>();
3008 GroupProperty prop = new GroupProperty();
3009 prop.setName(Constants.IS_BASE);
3010 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
3011 properties.add(prop);
3012 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
3013 if (getLatestGroupTypeRes.isRight()) {
3014 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
3016 properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
3017 groupDefinition.convertFromGroupProperties(properties);
3018 log.debug("createGroup start");
3020 // Since in these groups we handle only artifacts, then no need to
3021 // fetch component instances
3023 // Either<GroupDefinition, ResponseFormat> createGroup = groupBusinessLogic.createGroup(comp, user, ComponentTypeEnum.RESOURCE, groupDefinition, inTransaction);
3024 // log.debug("createGroup end");
3025 // if (createGroup.isRight())
3026 // return Either.right(createGroup.right().value());
3027 needToCreate.add(groupDefinition);
3030 ComponentParametersView componentParametersView = new ComponentParametersView();
3031 componentParametersView.disableAll();
3032 componentParametersView.setIgnoreUsers(false);
3033 componentParametersView.setIgnoreArtifacts(false);
3034 componentParametersView.setIgnoreGroups(false);
3036 componentParametersView.setIgnoreComponentInstances(false);
3038 Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
3039 if (component.isRight()) {
3040 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3043 Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate);
3044 if (createGroups.isRight()) {
3045 return Either.right(createGroups.right().value());
3051 public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
3052 Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
3053 vfModuleProperties.entrySet().forEach(p -> {
3054 GroupProperty prop = new GroupProperty();
3055 prop.setName(p.getKey());
3057 prop.setValue(p.getValue().getForBaseModule());
3058 prop.setDefaultValue(p.getValue().getForBaseModule());
3060 prop.setValue(p.getValue().getForNonBaseModule());
3061 prop.setDefaultValue(p.getValue().getForNonBaseModule());
3063 properties.add(prop);
3066 GroupProperty proplabel = new GroupProperty();
3067 proplabel.setName("vf_module_label");
3069 Matcher matcher = pattern.matcher(moduleName);
3071 if (matcher.find()) {
3072 proplabel.setValue(matcher.group(1));
3073 proplabel.setDefaultValue(matcher.group(1));
3075 proplabel.setValue(moduleName);
3076 proplabel.setDefaultValue(moduleName);
3078 properties.add(proplabel);
3080 GroupProperty propvolume = new GroupProperty();
3081 propvolume.setName("volume_group");
3082 boolean isVolume = false;
3083 for (String artifactId : artifactsInGroup) {
3084 ArtifactDefinition artifactDef = null;
3085 artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
3086 if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
3091 propvolume.setValue(String.valueOf(isVolume));
3092 propvolume.setDefaultValue(String.valueOf(isVolume));
3093 properties.add(propvolume);
3094 mergeWithGroupTypeProperties(properties, groupType.getProperties());
3098 private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
3100 Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
3101 for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
3102 if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
3103 properties.add(new GroupProperty(groupTypeProperty));
3108 private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
3109 for (ArtifactDefinition artifact : createdArtifacts) {
3110 if (artifact.getUniqueId().equals(artifactId)) {
3117 private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
3118 if (heatGroups != null && !heatGroups.isEmpty()) {
3119 for (GroupDefinition heatGroup : heatGroups) {
3120 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
3121 if (grpoupProps != null) {
3122 Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
3123 if (op.isPresent()) {
3124 GroupProperty prop = op.get();
3125 String heatFileNAme = prop.getValue();
3126 if (null == heatFileNAme || heatFileNAme.isEmpty())
3128 List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
3129 for (String artifactId : artifactsGroup) {
3130 Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3131 if (opArt.isPresent()) {
3132 artifacts.add(opArt.get());
3134 if (artifactsFromResource != null) {
3135 opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
3136 if (opArt.isPresent()) {
3137 artifacts.add(opArt.get());
3141 Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
3142 if (resOp.isPresent()) {
3143 members.putAll(heatGroup.getMembers());
3152 private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
3153 ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3154 Either<Resource, ResponseFormat> resStatus = Either.left(resource);
3155 String artifactFileName = artifactTemplateInfo.getFileName();
3156 String artifactUid = "";
3157 String artifactEnvUid = "";
3158 String artifactUUID = "";
3159 boolean alreadyExist = false;
3161 // check if artifacts already exist
3162 for (ArtifactDefinition createdArtifact : createdArtifacts) {
3163 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
3164 artifactUid = createdArtifact.getUniqueId();
3165 artifactUUID = createdArtifact.getArtifactUUID();
3166 if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3167 log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
3168 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3169 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
3171 alreadyExist = true;
3172 artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
3176 // if not exist need to create
3177 if (!alreadyExist) {
3179 Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3180 if (newArtifactEither.isRight()) {
3181 resStatus = Either.right(newArtifactEither.right().value());
3184 ArtifactDefinition newArtifact = newArtifactEither.left().value();
3185 artifactUid = newArtifact.getUniqueId();
3186 artifactUUID = newArtifact.getArtifactUUID();
3188 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
3189 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3190 Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
3191 resource.getName(), csarInfo.getModifier(), resource, null);
3192 if (createHeatEnvPlaceHolder.isRight()) {
3193 return Either.right(createHeatEnvPlaceHolder.right().value());
3195 artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
3199 artifactsGroup.add(artifactUid);
3200 artifactsUUIDGroup.add(artifactUUID);
3201 if (!artifactEnvUid.isEmpty()) {
3202 artifactsGroup.add(artifactEnvUid);
3205 List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3206 if (relatedArtifacts != null) {
3207 for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
3208 resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
3209 if (resStatus.isRight())
3216 private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
3217 String artifactEnvUid = "";
3218 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
3219 if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
3220 artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
3222 return artifactEnvUid;
3225 private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
3226 List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
3227 final String artifactFileName = artifactTemplateInfo.getFileName();
3228 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils);
3229 if (artifactContententStatus.isRight()) {
3230 return Either.right(artifactContententStatus.right().value());
3232 labelCounter += createdArtifacts.size();
3234 Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
3236 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
3237 shoudLock, inTransaction);
3239 if (uploadArtifactToService.isRight())
3240 return Either.right(uploadArtifactToService.right().value());
3242 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3243 if (currentInfo.getHeatParameters() != null) {
3245 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, false);
3246 if (updateEnvEither.isRight()) {
3247 log.debug("failed to update parameters to artifact {}", artifactFileName);
3248 return Either.right(updateEnvEither.right().value());
3251 currentInfo = updateEnvEither.left().value();
3255 createdArtifacts.add(currentInfo);
3257 return Either.left(currentInfo);
3261 private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
3262 List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
3264 Either<ArtifactDefinition, ResponseFormat> resStatus = null;
3265 String artifactFileName = artifactTemplateInfo.getFileName();
3267 // check if artifacts already exist
3268 for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
3269 if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
3270 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
3271 log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
3272 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3273 resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
3276 resStatus = Either.left(updatedArtifact);
3282 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
3283 if (artifactContententStatus.isRight()) {
3284 resStatus = Either.right(artifactContententStatus.right().value());
3288 Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
3289 oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
3291 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
3292 shouldLock, inTransaction);
3294 if (uploadArtifactToService.isRight()) {
3295 resStatus = Either.right(uploadArtifactToService.right().value());
3298 ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
3300 Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, true);
3301 if (updateEnvEither.isRight()) {
3302 log.debug("failed to update parameters to artifact {}", artifactFileName);
3303 resStatus = Either.right(updateEnvEither.right().value());
3306 // TODO evg update env time ( must be separate US for this!!!!)
3308 updatedArtifacts.add(updateEnvEither.left().value());
3309 resStatus = Either.left(updateEnvEither.left().value());
3315 private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
3316 Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
3317 if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
3319 Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
3321 if (artifactparamsStatus.isRight()) {
3322 resStatus = Either.right(artifactparamsStatus.right().value());
3325 Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
3327 * if (propsStatus.isRight()) {
3329 * resStatus = Either.right(propsStatus.right().value()); return resStatus; }
3331 if (propsStatus.isLeft()) {
3332 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
3333 List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
3334 // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3336 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3339 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3341 paramName = heatEnvParam.getName();
3342 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3343 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3345 String updatedParamValue = heatEnvParam.getCurrentValue();
3346 if (updatedParamValue == null)
3347 updatedParamValue = heatEnvParam.getDefaultValue();
3348 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3349 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3350 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3351 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3352 resStatus = Either.right(responseFormat);
3355 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3356 // newHeatEnvParams.add(currHeatParam);
3361 currentInfo.setListHeatParameters(currentHeatEnvParams);
3362 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
3363 if (updateArifactOnResource.isRight()) {
3364 log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
3365 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3367 resStatus = Either.left(updateArifactOnResource.left().value());
3372 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3373 Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
3374 if (op.isPresent()) {
3375 ArtifactDefinition artifactInfoHeatEnv = op.get();
3376 Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
3377 if (updateArifactOnResource.isRight()) {
3378 log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
3379 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
3386 private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
3387 // extract heat parameters
3388 String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
3389 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
3390 if (heatParameters.isRight()) {
3391 log.debug("File {} is not in expected key-value form in csar ", fileName);
3392 BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR);
3393 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
3396 return Either.left(heatParameters.left().value());
3400 private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) {
3402 Map<String, Object> json = new HashMap<String, Object>();
3403 String artifactName = artifactTemplateInfo.getFileName();
3405 json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
3406 json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
3407 json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
3409 // DE250204: There is no need to check if base64 encoding.
3411 // String encodedPayload = new String(artifactContentent);
3412 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3413 // if (!isEncoded) {
3414 String encodedPayload = Base64.encodeBase64String(artifactContentent);
3416 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3417 String displayName = artifactName;
3418 if (artifactName.lastIndexOf(".") > 0)
3419 displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
3420 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3421 String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
3422 json.put(Constants.ARTIFACT_LABEL, label);
3423 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
3424 List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
3425 json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
3426 : 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()));
3430 private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
3431 List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3433 Map<String, Object> json = new HashMap<String, Object>();
3434 if (artifactId != null && !artifactId.isEmpty())
3435 json.put(Constants.ARTIFACT_ID, artifactId);
3437 json.put(Constants.ARTIFACT_NAME, artifactName);
3438 json.put(Constants.ARTIFACT_TYPE, artifactType);
3439 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3441 String encodedPayload = new String(artifactContentent);
3443 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3444 // if (!isEncoded) {
3445 log.debug("payload is encoded. perform decode");
3446 encodedPayload = Base64.encodeBase64String(artifactContentent);
3449 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3450 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3451 json.put(Constants.ARTIFACT_LABEL, label);
3452 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3453 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3454 : 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()));
3458 @SuppressWarnings({ "unchecked", "static-access" })
3459 private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
3462 JsonObject jsonElement = new JsonObject();
3463 jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
3465 JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
3466 if (importStructureElement == null || importStructureElement.isJsonNull()) {
3467 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3468 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3469 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3472 Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>();
3473 artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
3474 if (artifactTemplateMap.isEmpty()) {
3475 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3476 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3477 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3480 Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
3481 Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>();
3482 List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
3483 for (String artifactsTypeKey : artifactsTypeKeys) {
3485 List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
3486 Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
3487 if (artifactTemplateInfoListPairStatus.isRight()) {
3488 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3489 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3490 return Either.right(artifactTemplateInfoListPairStatus.right().value());
3492 List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
3493 if (artifactTemplateInfoList == null) {
3494 log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
3495 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3496 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3499 allGroups.addAll(artifactTemplateInfoList);
3500 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList);
3502 int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
3503 Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
3504 if (validateGroupNamesRes.isRight()) {
3505 return Either.right(validateGroupNamesRes.right().value());
3507 return Either.left(artifactsMap);
3508 } catch (Exception e) {
3509 log.debug("Artifact file is not in expected format, fileName {}", artifactFileName);
3510 log.debug("failed with exception.", e);
3511 BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
3512 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
3517 private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) {
3518 List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>();
3519 for (Map<String, Object> o : jsonObject) {
3520 Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
3521 if (artifacttemplateInfoStatus.isRight()) {
3522 return Either.right(artifacttemplateInfoStatus.right().value());
3525 ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
3526 if (artifacttemplateInfo != null) {
3527 artifactTemplateInfoList.add(artifacttemplateInfo);
3531 return Either.left(artifactTemplateInfoList);
3534 private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3535 log.debug("createResourceInstancesRelations try to create relations ");
3536 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3537 if (uploadResInstancesMap == null) {
3538 log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
3539 BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR);
3541 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3542 return Either.right(responseFormat);
3545 if (componentInstancesList == null || componentInstancesList.isEmpty()) {
3546 log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
3547 BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3549 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3550 return Either.right(responseFormat);
3553 log.debug("Before validateAndUpdatePropertyValue");
3554 Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
3555 if (allDataTypes.isRight()) {
3556 TitanOperationStatus status = allDataTypes.right().value();
3557 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
3558 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
3562 Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
3563 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
3564 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
3565 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
3566 Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
3567 Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
3568 Map<String, Resource> originCompMap = new HashMap<>();
3569 List<RequirementCapabilityRelDef> relations = new ArrayList<>();
3571 Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
3573 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3574 log.trace("Processing entry: {}", entry);
3575 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3576 ComponentInstance currentCompInstance = null;
3577 for (ComponentInstance compInstance : componentInstancesList) {
3578 log.trace("Processing component instance: {}", compInstance);
3579 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3580 currentCompInstance = compInstance;
3585 if (currentCompInstance == null) {
3586 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3587 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3588 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3589 return Either.right(responseFormat);
3591 String resourceInstanceId = currentCompInstance.getUniqueId();
3592 Resource originResource;
3593 if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
3594 Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
3595 if (getOriginResourceRes.isRight()) {
3596 log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), getOriginResourceRes);
3597 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
3598 return Either.right(responseFormat);
3600 originResource = getOriginResourceRes.left().value();
3601 originCompMap.put(originResource.getUniqueId(), originResource);
3603 originResource = originCompMap.get(currentCompInstance.getComponentUid());
3605 if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
3606 instCapabilties.put(currentCompInstance, originResource.getCapabilities());
3607 if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
3608 instRequirements.put(currentCompInstance, originResource.getRequirements());
3609 if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
3610 instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
3611 if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
3612 instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
3613 if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
3614 instAttributes.put(resourceInstanceId, originResource.getAttributes());
3615 if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
3616 ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
3617 if (addPropertiesValueToRiRes.getStatus() != 200) {
3618 return Either.right(addPropertiesValueToRiRes);
3621 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(originResource);
3622 if (genericResourceEither.isRight()) {
3623 return genericResourceEither;
3625 log.trace("************* Going to add inputs from from original resource {} to resource instance. ", originResource.getName());
3626 if (originResource.shouldGenerateInputs())
3627 generateInputsFromGenericTypeProperties(originResource, genericResourceEither.left().value());
3629 ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
3630 if (addInputValueToRiRes.getStatus() != 200) {
3631 return Either.right(addInputValueToRiRes);
3636 Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
3637 if (addPropToInst.isRight()) {
3638 log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
3639 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
3640 return Either.right(responseFormat);
3642 if (instInputs != null && !instInputs.isEmpty()) {
3643 Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
3644 if (addInputToInst.isRight()) {
3645 log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
3646 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
3647 return Either.right(responseFormat);
3650 StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
3651 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3652 log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3653 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3654 return Either.right(responseFormat);
3657 addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, 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.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
3665 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3666 log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3667 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3668 return Either.right(responseFormat);
3671 addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
3672 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3673 log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3674 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3675 return Either.right(responseFormat);
3678 ComponentParametersView parametersView = new ComponentParametersView();
3679 parametersView.disableAll();
3680 parametersView.setIgnoreComponentInstances(false);
3681 parametersView.setIgnoreComponentInstancesProperties(false);
3682 parametersView.setIgnoreCapabilities(false);
3683 parametersView.setIgnoreRequirements(false);
3685 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
3687 if (eitherGetResource.isRight()) {
3688 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3690 return Either.right(responseFormat);
3694 resource = eitherGetResource.left().value();
3696 for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
3697 UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
3698 ComponentInstance currentCompInstance = null;
3699 for (ComponentInstance compInstance : componentInstancesList) {
3701 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3702 currentCompInstance = compInstance;
3707 if (currentCompInstance == null) {
3708 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3709 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3710 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3711 return Either.right(responseFormat);
3714 ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
3715 if (addRelationToRiRes.getStatus() != 200) {
3716 return Either.right(addRelationToRiRes);
3720 addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
3721 if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
3722 log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
3723 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
3724 return Either.right(responseFormat);
3727 log.debug("************* in create relations, getResource start");
3729 eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
3730 log.debug("************* in create relations, getResource end");
3731 if (eitherGetResource.isRight()) {
3732 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3734 return Either.right(responseFormat);
3737 resource = eitherGetResource.left().value();
3738 if(resource.getResourceType() == ResourceTypeEnum.CVFC){
3739 eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
3740 if (eitherGetResource.isRight()) {
3741 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
3742 return Either.right(responseFormat);
3745 return Either.left(eitherGetResource.left().value());
3748 private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
3749 Either<Resource, StorageOperationStatus> updateRes = null;
3750 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
3751 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
3752 StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements( resource.getUniqueId());
3753 if(status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND){
3754 log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", resource.getUniqueId(), status);
3755 updateRes = Either.right(status);
3757 if(updateRes == null){
3758 fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities, updatedInstRequirements);
3759 status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource.getUniqueId());
3760 if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
3761 log.debug("Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", resource.getUniqueId(), status);
3762 updateRes = Either.right(status);
3765 if(updateRes == null){
3766 updateRes = toscaOperationFacade.getToscaElement( resource.getUniqueId());
3772 private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
3773 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
3775 componentInstances.stream().forEach( i -> {
3776 fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
3777 fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
3781 private void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
3782 Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
3783 Set<String> updatedReqNames = new HashSet<>();
3784 if(MapUtils.isNotEmpty(requirementsNamesToUpdate)){
3785 for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
3786 updatedRequirements.put(requirements.getKey(), requirements.getValue().stream()
3787 .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
3788 .map(r ->{r.setParentName(r.getName()); r.setName(requirementsNamesToUpdate.get(r.getName())); updatedReqNames.add(r.getName()); return r;})
3789 .collect(Collectors.toList()));
3792 if(MapUtils.isNotEmpty(updatedRequirements)){
3793 updatedInstRequirements.put(instance, updatedRequirements);
3797 private void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
3798 Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
3799 Set<String> updatedCapNames = new HashSet<>();
3800 if(MapUtils.isNotEmpty(capabilitiesNamesToUpdate)){
3801 for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
3802 updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream()
3803 .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
3804 .map(c -> {c.setParentName(c.getName()); c.setName(capabilitiesNamesToUpdate.get(c.getName())); updatedCapNames.add(c.getName()); return c;})
3805 .collect(Collectors.toList()));
3808 if(MapUtils.isNotEmpty(updatedCapabilities)){
3809 updatedInstCapabilties.put(instance, updatedCapabilities);
3813 private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
3814 List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
3816 UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
3818 ComponentInstance currentCompInstance = null;
3820 for (ComponentInstance compInstance : componentInstancesList) {
3822 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
3823 currentCompInstance = compInstance;
3829 if (currentCompInstance == null) {
3830 log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
3831 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3832 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3833 return responseFormat;
3835 String resourceInstanceId = currentCompInstance.getUniqueId();
3837 Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
3839 if (regMap != null) {
3840 Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
3842 while (nodesRegValue.hasNext()) {
3843 Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
3845 List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
3846 for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
3847 log.debug("Going to create relation {}", uploadRegInfo.getName());
3848 String regName = uploadRegInfo.getName();
3849 RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
3850 regCapRelDef.setFromNode(resourceInstanceId);
3851 log.debug("try to find available requirement {} ", regName);
3852 Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
3853 if (eitherReqStatus.isRight()) {
3854 log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
3855 return eitherReqStatus.right().value();
3858 RequirementDefinition validReq = eitherReqStatus.left().value();
3859 List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
3860 if (reqAndRelationshipPairList == null)
3861 reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
3862 RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
3863 reqAndRelationshipPair.setRequirement(regName);
3864 reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
3865 reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
3866 RelationshipImpl relationship = new RelationshipImpl();
3867 relationship.setType(validReq.getCapability());
3868 reqAndRelationshipPair.setRelationships(relationship);
3870 ComponentInstance currentCapCompInstance = null;
3871 for (ComponentInstance compInstance : componentInstancesList) {
3872 if (compInstance.getName().equals(uploadRegInfo.getNode())) {
3873 currentCapCompInstance = compInstance;
3878 if (currentCapCompInstance == null) {
3879 log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
3880 BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
3881 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3882 return responseFormat;
3884 regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
3885 log.debug("try to find aviable Capability req name is {} ", validReq.getName());
3886 CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
3887 if (aviableCapForRel == null) {
3888 log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
3889 BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
3890 ErrorSeverity.ERROR);
3891 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
3892 return responseFormat;
3894 reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
3895 reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
3896 reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
3897 reqAndRelationshipPairList.add(reqAndRelationshipPair);
3898 regCapRelDef.setRelationships(reqAndRelationshipPairList);
3899 relations.add(regCapRelDef);
3902 } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
3903 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
3904 return responseFormat;
3906 return componentsUtils.getResponseFormat(ActionStatus.OK);
3909 private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
3910 Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
3911 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
3912 if (propMap != null && propMap.size() > 0) {
3913 Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
3915 List<InputDefinition> listFromMap = originResource.getInputs();
3916 if (listFromMap == null || listFromMap.isEmpty()) {
3917 log.debug("failed to find properties ");
3918 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
3919 return responseFormat;
3921 for (InputDefinition prop : listFromMap) {
3922 String propName = prop.getName();
3923 if (!currPropertiesMap.containsKey(propName)) {
3924 currPropertiesMap.put(propName, prop);
3927 List<ComponentInstanceInput> instPropList = new ArrayList<>();
3928 for (List<UploadPropInfo> propertyList : propMap.values()) {
3930 UploadPropInfo propertyInfo = propertyList.get(0);
3931 String propName = propertyInfo.getName();
3932 if (!currPropertiesMap.containsKey(propName)) {
3933 log.debug("failed to find property {} ", propName);
3934 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
3935 return responseFormat;
3937 InputDefinition curPropertyDef = currPropertiesMap.get(propName);
3938 ComponentInstanceInput property = null;
3940 String value = null;
3941 List<GetInputValueDataDefinition> getInputs = null;
3942 boolean isValidate = true;
3943 if (propertyInfo.getValue() != null) {
3944 getInputs = propertyInfo.getGet_input();
3945 isValidate = getInputs == null || getInputs.isEmpty();
3947 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
3949 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
3951 String innerType = null;
3952 property = new ComponentInstanceInput(curPropertyDef, value, null);
3954 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
3955 if (validatevalueEiter.isRight()) {
3956 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
3959 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
3960 // property.setUniqueId(uniqueId);
3961 property.setValue(validatevalueEiter.left().value());
3963 if (getInputs != null && !getInputs.isEmpty()) {
3964 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
3965 for (GetInputValueDataDefinition getInput : getInputs) {
3966 List<InputDefinition> inputs = resource.getInputs();
3967 if (inputs == null || inputs.isEmpty()) {
3968 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
3969 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3972 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
3973 if (!optional.isPresent()) {
3974 log.debug("Failed to find input {} ", getInput.getInputName());
3975 // @@TODO error message
3976 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3978 InputDefinition input = optional.get();
3979 getInput.setInputId(input.getUniqueId());
3980 getInputValues.add(getInput);
3982 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
3983 if (getInputIndex != null) {
3984 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
3985 if (!optional.isPresent()) {
3986 log.debug("Failed to find input {} ", getInputIndex.getInputName());
3987 // @@TODO error message
3988 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3990 InputDefinition inputIndex = optional.get();
3991 getInputIndex.setInputId(inputIndex.getUniqueId());
3992 getInputValues.add(getInputIndex);
3995 property.setGetInputValues(getInputValues);
3997 instPropList.add(property);
3998 // delete overriden property
3999 currPropertiesMap.remove(property.getName());
4001 // add rest of properties
4002 if (!currPropertiesMap.isEmpty()) {
4003 for (InputDefinition value : currPropertiesMap.values()) {
4004 instPropList.add(new ComponentInstanceInput(value));
4007 instInputs.put(currentCompInstance.getUniqueId(), instPropList);
4009 return componentsUtils.getResponseFormat(ActionStatus.OK);
4012 private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
4013 Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
4015 Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
4016 if (propMap != null && propMap.size() > 0) {
4017 Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
4019 List<PropertyDefinition> listFromMap = originResource.getProperties();
4020 if (listFromMap == null || listFromMap.isEmpty()) {
4021 log.debug("failed to find properties ");
4022 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
4023 return responseFormat;
4025 for (PropertyDefinition prop : listFromMap) {
4026 String propName = prop.getName();
4027 if (!currPropertiesMap.containsKey(propName)) {
4028 currPropertiesMap.put(propName, prop);
4031 List<ComponentInstanceProperty> instPropList = new ArrayList<>();
4032 for (List<UploadPropInfo> propertyList : propMap.values()) {
4034 UploadPropInfo propertyInfo = propertyList.get(0);
4035 String propName = propertyInfo.getName();
4036 if (!currPropertiesMap.containsKey(propName)) {
4037 log.debug("failed to find property {} ", propName);
4038 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
4039 return responseFormat;
4041 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
4042 ComponentInstanceProperty property = null;
4044 String value = null;
4045 List<GetInputValueDataDefinition> getInputs = null;
4046 boolean isValidate = true;
4047 if (propertyInfo.getValue() != null) {
4048 getInputs = propertyInfo.getGet_input();
4049 isValidate = getInputs == null || getInputs.isEmpty();
4051 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
4053 value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
4055 String innerType = null;
4056 property = new ComponentInstanceProperty(curPropertyDef, value, null);
4058 Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
4059 if (validatevalueEiter.isRight()) {
4060 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
4063 // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
4064 // property.setUniqueId(uniqueId);
4065 property.setValue(validatevalueEiter.left().value());
4067 if (getInputs != null && !getInputs.isEmpty()) {
4068 List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
4069 for (GetInputValueDataDefinition getInput : getInputs) {
4070 List<InputDefinition> inputs = resource.getInputs();
4071 if (inputs == null || inputs.isEmpty()) {
4072 log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
4073 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4076 Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
4077 if (!optional.isPresent()) {
4078 log.debug("Failed to find input {} ", getInput.getInputName());
4079 // @@TODO error message
4080 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4082 InputDefinition input = optional.get();
4083 getInput.setInputId(input.getUniqueId());
4084 getInputValues.add(getInput);
4086 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
4087 if (getInputIndex != null) {
4088 optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
4089 if (!optional.isPresent()) {
4090 log.debug("Failed to find input {} ", getInputIndex.getInputName());
4091 // @@TODO error message
4092 return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
4094 InputDefinition inputIndex = optional.get();
4095 getInputIndex.setInputId(inputIndex.getUniqueId());
4096 getInputValues.add(getInputIndex);
4101 property.setGetInputValues(getInputValues);
4103 instPropList.add(property);
4104 // delete overriden property
4105 currPropertiesMap.remove(property.getName());
4107 // add rest of properties
4108 if (!currPropertiesMap.isEmpty()) {
4109 for (PropertyDefinition value : currPropertiesMap.values()) {
4110 instPropList.add(new ComponentInstanceProperty(value));
4113 instProperties.put(currentCompInstance.getUniqueId(), instPropList);
4115 return componentsUtils.getResponseFormat(ActionStatus.OK);
4118 // US740820 Relate RIs according to capability name
4119 private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4120 if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
4124 return findAviableCapability(validReq, currentCapCompInstance);
4126 return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
4129 private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
4130 CapabilityDefinition cap = null;
4131 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4132 if (!capMap.containsKey(validReq.getCapability())) {
4135 Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
4136 if (!capByName.isPresent()) {
4139 cap = capByName.get();
4141 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4142 String leftOccurrences = cap.getLeftOccurrences();
4143 int left = Integer.parseInt(leftOccurrences);
4146 cap.setLeftOccurrences(String.valueOf(left));
4152 // TODO temporary fix - remove specific capability node validation -
4153 // String reqNode = validReq.getNode();
4154 // if (reqNode != null && !reqNode.isEmpty() &&
4155 // !cap.getCapabilitySources().contains(reqNode)) {
4158 // RequirementAndRelationshipPair relationPair = getReqRelPair(cap);
4159 // Either<Boolean, StorageOperationStatus> eitherStatus = componentInstanceOperation.isAvailableCapabilty(currentCapCompInstance, relationPair);
4160 // if (eitherStatus.isRight() || eitherStatus.left().value() == false) {
4166 private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
4167 CapabilityDefinition aviableCapForRel = null;
4168 Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
4169 if (capMap.containsKey(validReq.getCapability())) {
4170 List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
4172 for (CapabilityDefinition cap : capList) {
4173 // TODO temporary fix - remove specific capability node
4174 // String reqNode = validReq.getNode();
4175 // if (reqNode != null && !reqNode.isEmpty()) {
4176 // if (!cap.getCapabilitySources().contains(reqNode)) {
4180 if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
4181 String leftOccurrences = cap.getLeftOccurrences();
4182 if (leftOccurrences == null) {
4183 leftOccurrences = cap.getMaxOccurrences();
4185 int left = Integer.parseInt(leftOccurrences);
4188 cap.setLeftOccurrences(String.valueOf(left));
4189 aviableCapForRel = cap;
4195 aviableCapForRel = cap;
4200 return aviableCapForRel;
4203 private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
4204 Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
4205 List<RequirementDefinition> list = comInstRegDefMap.get(capName);
4206 RequirementDefinition validRegDef = null;
4208 for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
4209 for (RequirementDefinition reqDef : entry.getValue()) {
4210 if (reqDef.getName().equals(regName)) {
4211 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4212 String leftOccurrences = reqDef.getLeftOccurrences();
4213 if (leftOccurrences == null) {
4214 leftOccurrences = reqDef.getMaxOccurrences();
4216 int left = Integer.parseInt(leftOccurrences);
4219 reqDef.setLeftOccurrences(String.valueOf(left));
4220 validRegDef = reqDef;
4226 validRegDef = reqDef;
4232 if (validRegDef != null) {
4237 for (RequirementDefinition reqDef : list) {
4238 if (reqDef.getName().equals(regName)) {
4239 if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
4240 String leftOccurrences = reqDef.getLeftOccurrences();
4241 if (leftOccurrences == null) {
4242 leftOccurrences = reqDef.getMaxOccurrences();
4244 int left = Integer.parseInt(leftOccurrences);
4247 reqDef.setLeftOccurrences(String.valueOf(left));
4248 validRegDef = reqDef;
4254 validRegDef = reqDef;
4260 if (validRegDef == null) {
4261 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4262 return Either.right(responseFormat);
4264 return Either.left(validRegDef);
4267 public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
4269 Map<String, Object> mappedToscaTemplate;
4270 if(nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)){
4271 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
4275 //DE154502 Fail if duplicate key found in file
4276 mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
4278 } catch(ParserException e) {
4279 log.error("Failed to load yaml file {}", yamlFileName, e);
4280 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, yamlFileName, e.getMessage());
4281 return Either.right(responseFormat);
4284 Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
4285 if (toscaElementEither.isRight()) {
4286 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4287 return Either.right(responseFormat);
4290 Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4291 if (createInputsEither.isRight()) {
4292 ResponseFormat responseFormat = createInputsEither.right().value();
4293 return Either.right(responseFormat);
4296 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
4297 if (uploadResInstancesEither.isRight()) {
4298 ResponseFormat responseFormat = uploadResInstancesEither.right().value();
4299 return Either.right(responseFormat);
4302 Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource);
4303 if (createGroupsFromYaml.isRight()) {
4304 ResponseFormat responseFormat = createGroupsFromYaml.right().value();
4305 return Either.right(responseFormat);
4308 ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
4309 parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
4310 parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
4311 parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
4313 return Either.left(parsedToscaYamlInfo);
4316 private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
4317 Map<String, Resource> nodeNamespaceMap) {
4319 Either<Resource, ResponseFormat> eitherResource = null;
4320 log.debug("{} - going to create resource instanse from CSAR", yamlName);
4321 if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
4322 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4324 return Either.right(responseFormat);
4327 Map<String, Resource> existingnodeTypeMap = new HashMap<>();
4328 if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) {
4329 nodeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
4332 Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
4333 Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
4334 while (nodesInfoValue.hasNext()) {
4335 log.debug("*************Going to create resource instances from {}", yamlName);
4336 Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
4337 UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
4339 // updating type if the type is node type name - we need to take the
4341 log.debug("*************Going to create resource instance {}", uploadComponentInstanceInfo.getName());
4342 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4343 uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
4346 eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
4347 if (eitherResource.isRight()) {
4348 return eitherResource;
4350 Resource refResource = eitherResource.left().value();
4352 ComponentInstance componentInstance = new ComponentInstance();
4354 componentInstance.setComponentUid(refResource.getUniqueId());
4356 ComponentTypeEnum containerComponentType = resource.getComponentType();
4357 NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
4359 if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils.isNotEmpty(refResource.getCapabilities())) {
4360 setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4361 Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
4362 if (getValidComponentInstanceCapabilitiesRes.isRight()) {
4363 return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
4365 componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
4368 //***********************
4369 if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
4370 log.debug("createResourceInstances - not found latest version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4371 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4372 return Either.right(responseFormat);
4374 Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
4375 componentInstance.setName(uploadComponentInstanceInfo.getName());
4376 componentInstance.setIcon(origResource.getIcon());
4378 resourcesInstancesMap.put(componentInstance, origResource);
4381 if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
4383 StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
4384 if (status != null && status != StorageOperationStatus.OK) {
4385 log.debug("Failed to add component instances to container component {}", resource.getName());
4386 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
4387 eitherResource = Either.right(responseFormat);
4388 return eitherResource;
4393 log.debug("*************Going to get resource {}", resource.getUniqueId());
4394 ComponentParametersView parametersView = new ComponentParametersView();
4395 parametersView.disableAll();
4396 parametersView.setIgnoreComponentInstances(false);
4397 parametersView.setIgnoreUsers(false);
4398 parametersView.setIgnoreInputs(false); // inputs are read when creating
4399 // property values on instances
4400 Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
4401 log.debug("*************finished to get resource {}", resource.getUniqueId());
4402 if (eitherGerResource.isRight()) {
4403 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
4405 return Either.right(responseFormat);
4409 if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
4411 log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
4412 BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty");
4413 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
4414 return Either.right(responseFormat);
4418 return Either.left(eitherGerResource.left().value());
4421 private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
4422 for(Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()){
4423 if(originCapabilities.containsKey(currEntry.getKey())){
4424 currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
4428 for(Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()){
4429 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());});};});
4435 private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
4436 log.debug("going to validate resource instance with name {} and type {} before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4437 Resource refResource = null;
4438 if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
4439 refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
4441 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
4442 if (findResourceEither.isRight()) {
4443 log.debug("not found lates version for resource instance with name {} and type {}", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4444 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
4445 return Either.right(responseFormat);
4447 refResource = findResourceEither.left().value();
4448 nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
4450 String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
4451 if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4452 log.debug("component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState);
4453 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
4454 return Either.right(responseFormat);
4457 if (!ToscaUtils.isAtomicType(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
4458 log.debug("ref resource type is {}", refResource.getResourceType());
4459 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4460 return Either.right(responseFormat);
4462 log.debug("validate resource instance with name {} and type {} before create, successful",uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
4463 return Either.left(refResource);
4466 private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) {
4467 Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
4468 Map<String, Object> substitutionMappings = null;
4469 Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
4470 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
4471 Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
4472 if (eitherSubstitutionMappings.isLeft()) {
4473 substitutionMappings = eitherSubstitutionMappings.left().value();
4475 if (eitherNodesTemlates.isLeft()) {
4476 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
4478 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
4479 while (nodesNameValue.hasNext()) {
4480 Entry<String, Object> nodeNameValue = nodesNameValue.next();
4481 Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
4482 if (eitherNode.isRight()) {
4483 log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
4484 return Either.right(eitherNode.right().value());
4486 UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
4487 moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
4493 if (moduleComponentInstances.isEmpty()) {
4494 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
4495 return Either.right(responseFormat);
4501 @SuppressWarnings("unchecked")
4502 private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) {
4504 UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
4505 Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
4506 nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
4508 if (nodeTemplateJsonEntry.getValue() instanceof String) {
4509 String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
4510 nodeTemplateInfo.setType(nodeTemplateJsonString);
4511 } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
4512 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
4514 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4515 String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
4516 if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
4517 toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
4519 nodeTemplateInfo.setType(toscaResourceType);
4522 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4523 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4524 if (regResponse.isRight())
4525 return Either.right(regResponse.right().value());
4526 if (regResponse.left().value().size() > 0) {
4527 nodeTemplateInfo.setRequirements(regResponse.left().value());
4531 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4532 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
4533 if (eitherCapRes.isRight())
4534 return Either.right(eitherCapRes.right().value());
4535 if (eitherCapRes.left().value().size() > 0) {
4536 nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
4539 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4540 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4541 if (regResponse.isRight())
4542 return Either.right(regResponse.right().value());
4543 if (regResponse.left().value().size() > 0) {
4544 nodeTemplateInfo.setProperties(regResponse.left().value());
4547 if (substitutionMappings != null) {
4548 if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
4549 Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
4550 if (getCapNamesToUpdateRes.isRight())
4551 return Either.right(getCapNamesToUpdateRes.right().value());
4552 if (getCapNamesToUpdateRes.left().value().size() > 0) {
4553 nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
4556 if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
4557 Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
4558 if (getReqNamesToUpdateRes.isRight())
4559 return Either.right(getReqNamesToUpdateRes.right().value());
4560 if (getReqNamesToUpdateRes.left().value().size() > 0) {
4561 nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
4567 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
4570 } catch (Exception e) {
4571 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
4572 log.debug("error when creating capability, message:{}", e.getMessage(), e);
4573 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
4579 private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) {
4580 Either<Map<String, String>, ResponseFormat> response;
4582 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()));
4583 response = Either.left(namesToUpdate);
4584 } catch (Exception e) {
4585 log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName());
4586 response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4591 @SuppressWarnings("unchecked")
4592 private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
4593 Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
4594 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
4595 Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
4596 if (toscaProperties.isLeft()) {
4597 Map<String, Object> jsonProperties = toscaProperties.left().value();
4598 for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
4600 String propName = jsonPropObj.getKey();
4601 Object propValue = jsonPropObj.getValue();
4603 if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
4604 log.trace("Ignore property value {}.", propName);
4608 if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
4609 log.trace("Ignore property value {}.", propName);
4612 if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
4613 log.trace("Ignore property value {}.", propName);
4617 if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
4618 log.trace("Ignore property value {}.", propName);
4622 UploadPropInfo propertyDef = new UploadPropInfo();
4623 propertyDef.setValue(propValue);
4624 propertyDef.setName(propName);
4625 if (propValue instanceof Map) {
4626 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4627 propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
4630 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
4631 || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4632 createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
4635 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
4636 propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
4638 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
4639 propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
4641 if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
4642 propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
4644 propertyDef.setValue(propValue);
4646 } else if (propValue instanceof List) {
4647 List<Object> propValueList = (List<Object>) propValue;
4649 createInputPropList(propertyDef, propValueList);
4650 propertyDef.setValue(propValue);
4653 if (moduleProp.containsKey(propName)) {
4654 moduleProp.get(propName).add(propertyDef);
4656 List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
4657 list.add(propertyDef);
4658 moduleProp.put(propName, list);
4665 @SuppressWarnings("unchecked")
4666 private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
4667 for (Object objValue : propValueList) {
4669 if (objValue instanceof Map) {
4670 Map<String, Object> objMap = (Map<String, Object>) objValue;
4671 if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
4672 createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
4674 Set<String> keys = objMap.keySet();
4675 for (String key : keys) {
4676 Object value = objMap.get(key);
4677 if (value instanceof Map) {
4678 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4680 } else if (value instanceof List) {
4681 List<Object> propSubValueList = (List<Object>) value;
4683 createInputPropList(propertyDef, propSubValueList);
4689 } else if (objValue instanceof List) {
4690 List<Object> propSubValueList = (List<Object>) objValue;
4692 createInputPropList(propertyDef, propSubValueList);
4699 @SuppressWarnings("unchecked")
4700 private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
4702 if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4703 Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4704 GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
4705 List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
4706 if (getInputs == null) {
4707 getInputs = new ArrayList<GetInputValueDataDefinition>();
4709 if (getInput instanceof String) {
4711 getInputInfo.setInputName((String) getInput);
4712 getInputInfo.setPropName(propName);
4714 } else if (getInput instanceof List) {
4715 List<Object> getInputList = (List<Object>) getInput;
4716 getInputInfo.setPropName(propName);
4717 getInputInfo.setInputName((String) getInputList.get(0));
4718 if (getInputList.size() > 1) {
4719 Object indexObj = getInputList.get(1);
4720 if (indexObj instanceof Integer) {
4721 getInputInfo.setIndexValue((Integer) indexObj);
4722 } else if (indexObj instanceof Float) {
4723 int index = ((Float) indexObj).intValue();
4724 getInputInfo.setIndexValue(index);
4725 } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
4726 Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
4727 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
4728 getInputInfoIndex.setInputName((String) index);
4729 getInputInfoIndex.setPropName(propName);
4730 getInputInfo.setGetInputIndex(getInputInfoIndex);
4732 getInputInfo.setList(true);
4736 getInputs.add(getInputInfo);
4737 propertyDef.setGet_input(getInputs);
4738 propertyDef.setValue(propValue);
4740 Set<String> keys = propValue.keySet();
4741 for (String key : keys) {
4742 Object value = propValue.get(key);
4743 if (value instanceof Map) {
4744 createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
4746 } else if (value instanceof List) {
4747 List<Object> valueList = (List<Object>) value;
4748 for (Object o : valueList) {
4749 if (o instanceof Map) {
4750 createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
4763 * private boolean valueContainsStrReplace(Object propValue) {
4765 * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher =
4766 * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); }
4770 * private boolean valueContainsToken(Object propValue) {
4772 * 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 =
4778 private boolean valueContainsPattern(Pattern pattern, Object propValue) {
4780 log.debug("valueContainsToken value is {}", propValue);
4781 boolean result = false;
4782 if (propValue != null) {
4783 log.trace("valueContainspattern value is {}", propValue.getClass());
4784 Matcher matcher = pattern.matcher(propValue.toString());
4785 result = matcher.find();
4792 @SuppressWarnings("unchecked")
4793 private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4794 Map<String, List<UploadCapInfo>> moduleCap = new HashMap<String, List<UploadCapInfo>>();
4795 Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
4796 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
4797 if (toscaRequirements.isLeft()) {
4798 List<Object> jsonCapabilities = toscaRequirements.left().value();
4800 for (Object jsonCapObj : jsonCapabilities) {
4802 Map<String, Object> capJsonWrapper = (Map<String, Object>) jsonCapObj;
4803 String capName = capJsonWrapper.keySet().iterator().next();
4804 Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJsonWrapper.get(capName));
4805 if (eitherCap.isRight()) {
4806 log.info("error when creating Requirement:{}, for node:{}", capName, nodeTemplateInfo);
4807 return Either.right(eitherCap.right().value());
4809 UploadCapInfo requirementDef = eitherCap.left().value();
4810 requirementDef.setName(capName);
4811 if (moduleCap.containsKey(capName)) {
4812 moduleCap.get(capName).add(requirementDef);
4814 List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
4815 list.add(requirementDef);
4816 moduleCap.put(capName, list);
4824 @SuppressWarnings("unchecked")
4825 private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
4826 Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
4827 Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
4828 Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
4829 if (toscaRequirements.isLeft()) {
4830 List<Object> jsonRequirements = toscaRequirements.left().value();
4832 for (Object jsonRequirementObj : jsonRequirements) {
4834 Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
4835 String requirementName = requirementJsonWrapper.keySet().iterator().next();
4836 Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJsonWrapper.get(requirementName));
4837 if (eitherRequirement.isRight()) {
4838 log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
4839 return Either.right(eitherRequirement.right().value());
4841 UploadReqInfo requirementDef = eitherRequirement.left().value();
4842 requirementDef.setName(requirementName);
4843 if (moduleRequirements.containsKey(requirementName)) {
4844 moduleRequirements.get(requirementName).add(requirementDef);
4846 List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
4847 list.add(requirementDef);
4848 moduleRequirements.put(requirementName, list);
4856 @SuppressWarnings("unchecked")
4857 private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
4858 UploadCapInfo capTemplateInfo = new UploadCapInfo();
4859 Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
4861 if (capObject instanceof String) {
4862 String nodeTemplateJsonString = (String) capObject;
4863 capTemplateInfo.setNode(nodeTemplateJsonString);
4864 } else if (capObject instanceof Map) {
4865 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
4867 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4868 capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4870 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
4871 capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
4873 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
4874 Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
4875 if (validSourceTypesRes.isLeft()) {
4876 capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList()));
4879 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
4880 Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
4881 if (regResponse.isRight())
4882 return Either.right(regResponse.right().value());
4883 if (!regResponse.left().value().isEmpty()) {
4884 List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
4885 regResponse.left().value().values().forEach(list -> properties.addAll(list));
4886 if (!properties.isEmpty())
4887 capTemplateInfo.setProperties(properties);
4894 @SuppressWarnings("unchecked")
4895 private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
4897 UploadReqInfo regTemplateInfo = new UploadReqInfo();
4898 Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
4900 if (regObject instanceof String) {
4901 String nodeTemplateJsonString = (String) regObject;
4902 regTemplateInfo.setNode(nodeTemplateJsonString);
4903 } else if (regObject instanceof Map) {
4904 Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
4906 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
4907 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
4909 // US740820 Relate RIs according to capability name
4910 if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
4911 regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
4917 public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) {
4919 Either<Resource, ResponseFormat> result = null;
4921 if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())){
4922 result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4923 if(result.isRight()){
4926 resource = result.left().value();
4928 if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
4929 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
4930 result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
4933 return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
4934 } catch (Exception e) {
4935 log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName());
4936 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4938 if (result == null || result.isRight()) {
4939 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
4940 if (inTransaction == false) {
4941 log.debug("operation failed. do rollback");
4942 titanDao.rollback();
4944 } else if (inTransaction == false) {
4945 log.debug("operation success. do commit");
4951 private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4952 Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
4953 if (result.isLeft()) {
4954 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
4956 if (result.isLeft()) {
4957 result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
4962 private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
4963 return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
4969 * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
4972 * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
4973 * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
4976 public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo) {
4978 // check if resource already exist
4979 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
4980 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
4983 if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
4985 Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
4986 if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
4987 result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
4990 StorageOperationStatus status = latestByName.right().value();
4991 BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
4992 log.debug("resource already exist {}. status={}", resource.getName(), status);
4993 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
4994 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
4995 result = Either.right(responseFormat);
5001 else if (latestByName.isLeft()) {
5002 result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock);
5007 StorageOperationStatus status = latestByName.right().value();
5008 log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
5009 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
5010 componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
5011 result = Either.right(responseFormat);
5017 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
5018 log.debug("resource with name {} does not exist. create new resource", resource.getName());
5019 Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
5020 if (response.isRight()) {
5021 return Either.right(response.right().value());
5023 Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
5024 if (createResponse.isRight()) {
5025 return Either.right(createResponse.right().value());
5027 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
5028 ASDCKpiApi.countImportResourcesKPI();
5029 return Either.left(resourcePair);
5034 public boolean isResourceExist(String resourceName) {
5035 Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
5036 return latestByName.isLeft();
5039 private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock) {
5040 String lockedResourceId = oldResource.getUniqueId();
5041 log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState());
5042 Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
5045 Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import");
5046 if (lockResult.isRight()) {
5047 return Either.right(lockResult.right().value());
5051 Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false);
5052 if (prepareResourceForUpdate.isRight()) {
5053 ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
5054 log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage());
5055 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5056 result = Either.right(prepareResourceForUpdate.right().value());
5059 oldResource = prepareResourceForUpdate.left().value();
5061 mergeOldResourceMetadataWithNew(oldResource, newResource);
5063 Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction);
5064 if (validateFieldsResponse.isRight()) {
5065 result = Either.right(validateFieldsResponse.right().value());
5069 // contact info normalization
5070 newResource.setContactId(newResource.getContactId().toLowerCase());
5071 // non-updatable fields
5072 newResource.setCreatorUserId(user.getUserId());
5073 newResource.setCreatorFullName(user.getFullName());
5074 newResource.setLastUpdaterUserId(user.getUserId());
5075 newResource.setLastUpdaterFullName(user.getFullName());
5076 newResource.setUniqueId(oldResource.getUniqueId());
5077 newResource.setVersion(oldResource.getVersion());
5078 newResource.setInvariantUUID(oldResource.getInvariantUUID());
5079 newResource.setLifecycleState(oldResource.getLifecycleState());
5080 newResource.setUUID(oldResource.getUUID());
5081 newResource.setNormalizedName(oldResource.getNormalizedName());
5082 newResource.setSystemName(oldResource.getSystemName());
5083 if (oldResource.getCsarUUID() != null) {
5084 newResource.setCsarUUID(oldResource.getCsarUUID());
5086 if (oldResource.getImportedToscaChecksum() != null) {
5087 newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
5089 newResource.setAbstract(oldResource.isAbstract());
5091 if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
5092 newResource.setDerivedFrom(oldResource.getDerivedFrom());
5094 // TODO rhalili: handle artifacts here (delete from old resource and
5096 // TODO rbetzer: remove after migration - in case of resources
5097 // created without tosca artifacts - add the placeholders
5098 if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
5099 setToscaArtifactsPlaceHolders(newResource, user);
5101 Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
5103 if (overrideResource.isRight()) {
5104 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
5105 componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5106 result = Either.right(responseFormat);
5110 log.debug("Resource updated successfully!!!");
5111 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
5112 componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
5114 ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
5115 result = Either.left(resourcePair);
5118 if (result == null || result.isRight()) {
5119 BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
5120 log.debug("operation failed. do rollback");
5121 titanDao.rollback();
5122 } else if (inTransaction == false) {
5123 log.debug("operation success. do commit");
5126 if (needLock == true) {
5127 log.debug("unlock resource {}", lockedResourceId);
5128 graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
5135 * Merge old resource with new. Keep old category and vendor name without change
5137 * @param oldResource
5138 * @param newResource
5140 private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
5142 // keep old category and vendor name without change
5143 // merge the rest of the resource metadata
5144 if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
5145 newResource.setTags(oldResource.getTags());
5148 if (newResource.getDescription() == null) {
5149 newResource.setDescription(oldResource.getDescription());
5152 if (newResource.getVendorRelease() == null) {
5153 newResource.setVendorRelease(oldResource.getVendorRelease());
5156 if (newResource.getResourceVendorModelNumber() == null) {
5157 newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
5160 if (newResource.getContactId() == null) {
5161 newResource.setContactId(oldResource.getContactId());
5164 newResource.setCategories(oldResource.getCategories());
5165 newResource.setVendorName(oldResource.getVendorName());
5168 private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) {
5170 Either<Resource, ResponseFormat> result = Either.left(latestResource);
5171 // check if user can edit resource
5172 if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
5174 Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
5175 result = changeState;
5181 public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
5183 Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
5184 if (eitherValidation.isRight()) {
5185 return Either.right(eitherValidation.right().value());
5188 eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
5189 if (eitherValidation.isRight()) {
5190 return Either.right(eitherValidation.right().value());
5192 eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
5193 if (eitherValidation.isRight()) {
5194 return Either.right(eitherValidation.right().value());
5196 eitherValidation = validateResourceType(user, resource, actionEnum);
5197 if (eitherValidation.isRight()) {
5198 return Either.right(eitherValidation.right().value());
5201 resource.setCreatorUserId(user.getUserId());
5202 resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
5203 resource.setContactId(resource.getContactId().toLowerCase());
5204 if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ToscaUtils.isAtomicType(resource)) {
5205 String resourceSystemName;
5206 if(csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())){
5207 resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
5209 resourceSystemName = resource.getSystemName();
5211 resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
5214 // Generate invariant UUID - must be here and not in operation since it
5215 // should stay constant during clone
5217 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
5218 resource.setInvariantUUID(invariantUUID);
5220 return Either.left(resource);
5223 private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
5224 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5225 if (resource.getResourceType() == null) {
5226 log.debug("Invalid resource type for resource");
5227 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
5228 eitherResult = Either.right(errorResponse);
5229 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5231 return eitherResult;
5234 private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
5235 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5236 if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
5237 log.debug("validate interface lifecycle Types Exist");
5238 Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
5239 while (intItr.hasNext() && eitherResult.isLeft()) {
5240 InterfaceDefinition interfaceDefinition = intItr.next();
5241 String intType = interfaceDefinition.getUniqueId();
5242 Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
5243 if (eitherCapTypeFound.isRight()) {
5244 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5245 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
5246 log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
5247 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
5248 log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
5251 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
5252 eitherResult = Either.right(errorResponse);
5253 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5258 return eitherResult;
5261 private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5263 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
5264 if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
5265 log.debug("validate capability Types Exist - capabilities section");
5267 for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
5269 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
5270 if (eitherResult.isRight()) {
5271 return Either.right(eitherResult.right().value());
5276 if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
5277 log.debug("validate capability Types Exist - requirements section");
5278 for (String type : resource.getRequirements().keySet()) {
5279 eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
5280 if (eitherResult.isRight()) {
5281 return Either.right(eitherResult.right().value());
5286 return eitherResult;
5289 // @param typeObject- the object to which the validation is done
5290 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
5291 boolean inTransaction) {
5292 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
5293 if (eitherCapTypeFound.isRight()) {
5294 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5295 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
5296 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
5297 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5299 log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
5300 ResponseFormat errorResponse = null;
5302 errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
5304 errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
5305 eitherResult = Either.right(errorResponse);
5306 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5308 return eitherResult;
5311 private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
5312 Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
5313 Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
5314 if (eitherCapTypeFound.isRight()) {
5315 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
5316 BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
5317 log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
5318 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
5320 log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
5321 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
5322 eitherResult = Either.right(errorResponse);
5323 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
5325 CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
5326 if (capabilityTypeDefinition.getProperties() != null) {
5327 for (CapabilityDefinition capDef : typeEntry.getValue()) {
5328 List<ComponentInstanceProperty> properties = capDef.getProperties();
5329 if (properties == null || properties.isEmpty()) {
5330 properties = new ArrayList<ComponentInstanceProperty>();
5331 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5332 ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
5333 properties.add(newProp);
5336 for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
5337 PropertyDefinition porpFromDef = prop.getValue();
5338 List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
5339 for (ComponentInstanceProperty cip : properties) {
5340 if (!cip.getName().equals(porpFromDef.getName())) {
5341 ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
5342 propsToAdd.add(newProp);
5345 if (!propsToAdd.isEmpty()) {
5346 properties.addAll(propsToAdd);
5350 capDef.setProperties(properties);
5353 return eitherResult;
5356 public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5359 // lock new resource name in order to avoid creation resource with same
5361 if (inTransaction == false) {
5362 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
5363 if (lockResult.isRight()) {
5364 ResponseFormat responseFormat = lockResult.right().value();
5365 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
5366 return Either.right(responseFormat);
5369 log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
5372 if (resource.deriveFromGeneric()) {
5373 Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
5374 if (genericResourceEither.isRight())
5375 return genericResourceEither;
5376 if (resource.shouldGenerateInputs())
5377 generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
5380 Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
5381 if (respStatus.isLeft()) {
5382 auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams);
5383 ASDCKpiApi.countCreatedResourcesKPI();
5385 componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
5389 if (inTransaction == false) {
5390 graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
5395 private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
5396 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
5397 componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams);
5400 private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
5401 // validate resource name uniqueness
5402 log.debug("validate resource name");
5403 Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
5404 if (eitherValidation.isRight()) {
5405 log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
5406 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
5407 return Either.right(errorResponse);
5409 if (eitherValidation.left().value()) {
5410 log.debug("resource with name: {}, already exists", resource.getName());
5411 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
5412 return Either.right(errorResponse);
5415 log.debug("send resource {} to dao for create", resource.getName());
5417 createArtifactsPlaceHolderData(resource, user);
5423 log.debug("enrich resource with creator, version and state");
5424 resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
5425 resource.setVersion(INITIAL_VERSION);
5426 resource.setHighestVersion(true);
5427 if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
5428 resource.setAbstract(false);
5431 Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
5432 if (createToscaElement.isLeft()) {
5433 return Either.left(createToscaElement.left().value());
5436 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
5438 return Either.right(responseFormat);
5441 private void createArtifactsPlaceHolderData(Resource resource, User user) {
5442 // create mandatory artifacts
5444 // TODO it must be removed after that artifact uniqueId creation will be
5445 // moved to ArtifactOperation
5446 // String resourceUniqueId =
5447 // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
5448 // resource.getResourceVersion());
5450 setInformationalArtifactsPlaceHolder(resource, user);
5451 setDeploymentArtifactsPlaceHolder(resource, user);
5452 setToscaArtifactsPlaceHolders(resource, user);
5455 @SuppressWarnings("unchecked")
5457 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
5458 Resource resource = (Resource) component;
5459 Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
5460 if (artifactMap == null) {
5461 artifactMap = new HashMap<String, ArtifactDefinition>();
5463 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts();
5464 if (deploymentResourceArtifacts != null) {
5465 Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
5466 while (iterator.hasNext()) {
5467 Entry<String, Object> currEntry = iterator.next();
5468 boolean shouldCreateArtifact = true;
5469 Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
5470 Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
5471 if (object != null) {
5472 List<String> artifactTypes = (List<String>) object;
5473 if (!artifactTypes.contains(resource.getResourceType().name())) {
5474 shouldCreateArtifact = false;
5478 log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey());
5480 if (shouldCreateArtifact) {
5481 if (artifactsBusinessLogic != null) {
5482 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT);
5483 if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
5484 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5489 resource.setDeploymentArtifacts(artifactMap);
5492 @SuppressWarnings("unchecked")
5493 private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
5494 Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
5495 if (artifactMap == null) {
5496 artifactMap = new HashMap<String, ArtifactDefinition>();
5498 String resourceUniqueId = resource.getUniqueId();
5499 List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
5500 List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
5501 Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
5502 List<CategoryDefinition> categories = resource.getCategories();
5503 boolean isCreateArtifact = true;
5504 if (exludeResourceCategory != null) {
5505 String category = categories.get(0).getName();
5506 for (String exlude : exludeResourceCategory) {
5507 if (exlude.equalsIgnoreCase(category)) {
5508 isCreateArtifact = false;
5514 if (isCreateArtifact && exludeResourceType != null) {
5515 String resourceType = resource.getResourceType().name();
5516 for (String type : exludeResourceType) {
5517 if (type.equalsIgnoreCase(resourceType)) {
5518 isCreateArtifact = false;
5525 if (informationalResourceArtifacts != null && isCreateArtifact) {
5526 Set<String> keys = informationalResourceArtifacts.keySet();
5527 for (String informationalResourceArtifactName : keys) {
5528 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
5529 ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
5530 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
5534 resource.setArtifacts(artifactMap);
5544 public ResponseFormat deleteResource(String resourceId, User user) {
5545 ResponseFormat responseFormat;
5546 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5547 if (eitherCreator.isRight()) {
5548 return eitherCreator.right().value();
5551 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
5552 if (resourceStatus.isRight()) {
5553 log.debug("failed to get resource {}", resourceId);
5554 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
5557 Resource resource = resourceStatus.left().value();
5559 StorageOperationStatus result = StorageOperationStatus.OK;
5560 Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
5561 if (lockResult.isRight()) {
5562 result = StorageOperationStatus.GENERAL_ERROR;
5563 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5568 result = markComponentToDelete(resource);
5569 if (result.equals(StorageOperationStatus.OK)) {
5570 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5572 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5573 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5575 return responseFormat;
5578 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5579 log.warn("operation failed. do rollback");
5580 titanDao.rollback();
5582 log.debug("operation success. do commit");
5585 graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
5590 public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
5591 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
5592 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
5593 if (eitherCreator.isRight()) {
5594 return eitherCreator.right().value();
5597 // Resource resource = null;
5598 Resource resource = null;
5599 StorageOperationStatus result = StorageOperationStatus.OK;
5602 Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
5603 if (resourceStatus.isRight()) {
5604 log.debug("failed to get resource {} version {}", resourceName, version);
5605 return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
5608 resource = resourceStatus.left().value();
5611 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5612 log.warn("operation failed. do rollback");
5613 titanDao.rollback();
5614 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5615 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
5617 log.debug("operation success. do commit");
5621 if (resource != null) {
5622 Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
5623 if (lockResult.isRight()) {
5624 result = StorageOperationStatus.GENERAL_ERROR;
5625 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5628 result = markComponentToDelete(resource);
5629 if (!result.equals(StorageOperationStatus.OK)) {
5630 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
5631 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
5632 return responseFormat;
5636 if (result == null || !result.equals(StorageOperationStatus.OK)) {
5637 log.warn("operation failed. do rollback");
5638 titanDao.rollback();
5640 log.debug("operation success. do commit");
5643 graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
5646 return responseFormat;
5649 public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
5652 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
5653 if (eitherCreator.isRight()) {
5654 return Either.right(eitherCreator.right().value());
5658 // IResourceOperation dataModel = getResourceOperation();
5659 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
5660 if (storageStatus.isRight()) {
5661 log.debug("failed to get resource by id {}", resourceId);
5662 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
5664 if(!(storageStatus.left().value() instanceof Resource)){
5665 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
5667 return Either.left(storageStatus.left().value());
5671 public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
5673 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
5674 if (resp.isRight()) {
5675 return Either.right(resp.right().value());
5678 Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
5679 if (getResource.isRight()) {
5680 log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
5681 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
5683 return Either.left(getResource.left().value());
5687 * updateResourceMetadata
5689 * @param user - modifier data (userId)
5690 * @param inTransaction TODO
5691 * @param resourceIdToUpdate - the resource identifier
5692 * @param newResource
5693 * @return Either<Resource, responseFormat>
5695 public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
5697 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
5698 if (resp.isRight()) {
5699 return Either.right(resp.right().value());
5702 // IResourceOperation dataModel = getResourceOperation();
5703 log.debug("Get resource with id {}", resourceIdToUpdate);
5704 boolean needToUnlock = false;
5705 boolean rollbackNeeded = true;
5708 // Either<Resource, StorageOperationStatus> storageStatus =
5709 // dataModel.getResource_tx(resourceIdToUpdate, false);
5710 if (currentResource == null) {
5711 Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
5712 if (storageStatus.isRight()) {
5713 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
5716 currentResource = storageStatus.left().value();
5718 // verify that resource is checked-out and the user is the last
5720 if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
5721 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
5725 StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5726 if (!lockResult.equals(StorageOperationStatus.OK)) {
5727 BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
5728 log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
5729 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
5730 return Either.right(responseFormat);
5733 needToUnlock = true;
5735 // critical section starts here
5736 // convert json to object
5738 // Update and updated resource must have a non-empty "derivedFrom"
5740 // This code is not called from import resources, because of root
5741 // VF "derivedFrom" should be null (or ignored)
5742 if (ToscaUtils.isAtomicType(currentResource)) {
5743 Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
5744 if (derivedFromNotEmptyEither.isRight()) {
5745 log.debug("for updated resource {}, derived from field is empty", newResource.getName());
5746 return Either.right(derivedFromNotEmptyEither.right().value());
5749 derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
5750 if (derivedFromNotEmptyEither.isRight()) {
5751 log.debug("for current resource {}, derived from field is empty", currentResource.getName());
5752 return Either.right(derivedFromNotEmptyEither.right().value());
5755 newResource.setDerivedFrom(null);
5758 Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true);
5759 if (dataModelResponse.isRight()) {
5760 log.debug("failed to update resource metadata!!!");
5761 rollbackNeeded = true;
5762 return Either.right(dataModelResponse.right().value());
5765 log.debug("Resource metadata updated successfully!!!");
5766 rollbackNeeded = false;
5767 return Either.left(dataModelResponse.left().value());
5770 if (!inTransaction) {
5771 if (rollbackNeeded) {
5772 titanDao.rollback();
5779 graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
5784 private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){
5785 if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){
5786 if (log.isInfoEnabled())
5787 log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" );
5788 return Either.right(false);
5790 List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList());
5791 for ( GroupDefinition group : list) {
5792 if ( group!=null && group.isSamePrefix( replacePattern ) ){
5793 String prefix = group.getName().substring( 0, replacePattern.length() );
5794 String newGroupName = group.getName().replaceFirst(prefix , with);
5795 group.setName(newGroupName);
5796 //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id
5797 //group.setUniqueId(newUid);
5800 return Either.left(list);
5803 private boolean isComponentNameChanged(Resource newResource,Resource oldResource){
5804 if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional
5805 String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5806 String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
5807 return !oldName.equals(futureName);
5812 private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
5813 //region -> Update groups name for newResource
5814 if ( isComponentNameChanged( currentResource , newResource) ){
5815 String replacePattern = Optional.ofNullable( //get currentResource name from metadata
5816 Optional.ofNullable( Optional.ofNullable( currentResource )
5817 .orElse(null).getComponentMetadataDefinition() )
5818 .orElse(null).getMetadataDataDefinition() )
5819 .orElse(null).getName();
5820 String with = Optional.ofNullable( //get newResource name from metadata
5821 Optional.ofNullable( Optional.ofNullable( newResource )
5822 .orElse(null).getComponentMetadataDefinition() )
5823 .orElse(null).getMetadataDataDefinition() )
5824 .orElse(null).getName();
5825 if ( with != null && replacePattern != null ){
5826 Either<List<GroupDefinition>,Boolean> result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups());
5827 if (result.isLeft())
5828 newResource.setGroups( (List<GroupDefinition>)result.left().value() );
5833 Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
5834 if (validateResourceFields.isRight()) {
5835 return Either.right(validateResourceFields.right().value());
5837 // Setting last updater and uniqueId
5838 newResource.setContactId(newResource.getContactId().toLowerCase());
5839 newResource.setLastUpdaterUserId(user.getUserId());
5840 newResource.setUniqueId(resourceIdToUpdate);
5841 // Cannot set highest version through UI
5842 newResource.setHighestVersion(currentResource.isHighestVersion());
5843 newResource.setCreationDate(currentResource.getCreationDate());
5845 Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
5847 if (processUpdateOfDerivedFrom.isRight()) {
5848 log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
5849 return Either.right(processUpdateOfDerivedFrom.right().value());
5852 log.debug("send resource {} to dao for update", newResource.getUniqueId());
5853 if (newResource!=null && newResource.getGroups()!=null){
5854 for ( GroupDefinition group : newResource.getGroups() ){
5855 if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null)
5856 groupBusinessLogic.validateAndUpdateGroupMetadata(
5857 newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() ,
5859 ComponentTypeEnum.RESOURCE_INSTANCE,
5865 Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
5867 if (dataModelResponse.isRight()) {
5868 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
5869 return Either.right(responseFormat);
5870 } else if (dataModelResponse.left().value() == null) {
5871 log.debug("No response from updateResource");
5872 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5874 return Either.left(dataModelResponse.left().value());
5878 * validateResourceFieldsBeforeCreate
5880 * @param user - modifier data (userId)
5881 * @param dataModel - IResourceOperation for resource crud
5882 * @param resource - Resource object to validate
5883 * @return Either<Boolean, ErrorResponse>
5885 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
5886 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
5887 if (componentsFieldsValidation.isRight()) {
5888 return componentsFieldsValidation;
5894 * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5896 * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5901 * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5906 * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5909 // validate category
5910 log.debug("validate category");
5911 Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
5912 if (eitherValidation.isRight()) {
5913 return eitherValidation;
5916 // validate vendor name & release & model number
5917 log.debug("validate vendor name");
5918 eitherValidation = validateVendorName(user, resource, actionEnum);
5919 if (eitherValidation.isRight()) {
5920 return eitherValidation;
5923 log.debug("validate vendor release");
5924 eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
5925 if (eitherValidation.isRight()) {
5926 return eitherValidation;
5929 log.debug("validate resource vendor model number");
5930 eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
5931 if (eitherValidation.isRight()) {
5932 return eitherValidation;
5935 // validate contact info
5937 * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
5941 log.debug("validate cost");
5942 eitherValidation = validateCost(user, resource, actionEnum);
5943 if (eitherValidation.isRight()) {
5944 return eitherValidation;
5947 // validate licenseType
5948 log.debug("validate licenseType");
5949 eitherValidation = validateLicenseType(user, resource, actionEnum);
5950 if (eitherValidation.isRight()) {
5951 return eitherValidation;
5954 // validate template (derived from)
5955 log.debug("validate derived from");
5956 if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
5957 resource.setDerivedFrom(null);
5959 eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
5960 if (eitherValidation.isRight()) {
5961 return Either.right(eitherValidation.right().value());
5964 // warn about non-updatable fields
5965 checkComponentFieldsForOverrideAttempt(resource);
5966 String currentCreatorFullName = resource.getCreatorFullName();
5967 if (currentCreatorFullName != null) {
5968 log.warn("Resource Creator fullname is automatically set and cannot be updated");
5971 String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
5972 if (currentLastUpdaterFullName != null) {
5973 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
5976 Long currentLastUpdateDate = resource.getLastUpdateDate();
5977 if (currentLastUpdateDate != null) {
5978 log.warn("Resource last update date is automatically set and cannot be updated");
5981 Boolean currentAbstract = resource.isAbstract();
5982 if (currentAbstract != null) {
5983 log.warn("Resource abstract is automatically set and cannot be updated");
5986 return Either.left(true);
5990 * validateResourceFieldsBeforeUpdate
5992 * @param currentResource - Resource object to validate
5993 * @return Either<Boolean, ErrorResponse>
5995 private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
5997 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
5999 // validate resource name
6000 log.debug("validate resource name before update");
6001 Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified);
6002 if (eitherValidation.isRight()) {
6003 return eitherValidation;
6006 // validate description
6007 log.debug("validate description before update");
6008 eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
6009 if (eitherValidation.isRight()) {
6010 return eitherValidation;
6013 log.debug("validate icon before update");
6014 eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
6015 if (eitherValidation.isRight()) {
6016 return eitherValidation;
6019 log.debug("validate tags before update");
6020 eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
6021 if (eitherValidation.isRight()) {
6022 return eitherValidation;
6025 log.debug("validate vendor name before update");
6026 eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
6027 if (eitherValidation.isRight()) {
6028 return eitherValidation;
6031 log.debug("validate resource vendor model number before update");
6032 eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
6033 if (eitherValidation.isRight()) {
6034 return eitherValidation;
6038 log.debug("validate vendor release before update");
6039 eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
6040 if (eitherValidation.isRight()) {
6041 return eitherValidation;
6044 log.debug("validate contact info before update");
6045 eitherValidation = validateContactId(null, updateInfoResource, null);
6046 if (eitherValidation.isRight()) {
6047 return eitherValidation;
6050 log.debug("validate derived before update");
6051 eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
6052 if (eitherValidation.isRight()) {
6053 return eitherValidation;
6056 log.debug("validate category before update");
6057 eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
6058 if (eitherValidation.isRight()) {
6059 return eitherValidation;
6062 // warn about non-updatable fields
6063 String currentResourceVersion = currentResource.getVersion();
6064 String updatedResourceVersion = updateInfoResource.getVersion();
6066 if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
6067 log.warn("Resource version is automatically set and cannot be updated");
6070 String currentCreatorUserId = currentResource.getCreatorUserId();
6071 String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
6073 if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
6074 log.warn("Resource Creator UserId is automatically set and cannot be updated");
6077 String currentCreatorFullName = currentResource.getCreatorFullName();
6078 String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
6080 if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
6081 log.warn("Resource Creator fullname is automatically set and cannot be updated");
6084 String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
6085 String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
6087 if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
6088 log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
6091 String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
6092 String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
6094 if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
6095 log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
6098 Long currentCreationDate = currentResource.getCreationDate();
6099 Long updatedCreationDate = updateInfoResource.getCreationDate();
6101 if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
6102 log.warn("Resource Creation date is automatically set and cannot be updated");
6105 Long currentLastUpdateDate = currentResource.getLastUpdateDate();
6106 Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
6108 if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
6109 log.warn("Resource last update date is automatically set and cannot be updated");
6112 LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
6113 LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
6115 if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
6116 log.warn("Resource lifecycle state date is automatically set and cannot be updated");
6119 Boolean currentAbstract = currentResource.isAbstract();
6120 Boolean updatedAbstract = updateInfoResource.isAbstract();
6122 if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
6123 log.warn("Resource abstract is automatically set and cannot be updated");
6126 Boolean currentHighestVersion = currentResource.isHighestVersion();
6127 Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
6129 if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
6130 log.warn("Resource highest version is automatically set and cannot be updated");
6133 String currentUuid = currentResource.getUUID();
6134 String updatedUuid = updateInfoResource.getUUID();
6136 if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
6137 log.warn("Resource UUID is automatically set and cannot be updated");
6140 ResourceTypeEnum currentResourceType = currentResource.getResourceType();
6141 ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
6143 if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
6144 log.warn("Resource Type cannot be updated");
6147 updateInfoResource.setResourceType(currentResource.getResourceType());
6149 String currentInvariantUuid = currentResource.getInvariantUUID();
6150 String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
6152 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
6153 log.warn("Resource invariant UUID is automatically set and cannot be updated");
6154 updateInfoResource.setInvariantUUID(currentInvariantUuid);
6156 return Either.left(true);
6160 * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName();
6162 * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
6163 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); }
6165 * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.
6166 * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat);
6169 * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME,
6170 * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName(
6171 * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ;
6173 * return Either.left(true); }
6176 private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6177 String resourceNameUpdated = updateInfoResource.getName();
6178 String resourceNameCurrent = currentResource.getName();
6179 if (!resourceNameCurrent.equals(resourceNameUpdated)) {
6180 if (!hasBeenCertified) {
6181 Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null);
6182 if (validateResourceNameResponse.isRight()) {
6183 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6184 return Either.right(errorResponse);
6186 validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
6187 if (validateResourceNameResponse.isRight()) {
6188 ResponseFormat errorResponse = validateResourceNameResponse.right().value();
6189 return Either.right(errorResponse);
6191 currentResource.setName(resourceNameUpdated);
6192 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
6193 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
6196 log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
6197 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
6198 return Either.right(errorResponse);
6201 return Either.left(true);
6204 private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6205 String iconUpdated = updateInfoResource.getIcon();
6206 String iconCurrent = currentResource.getIcon();
6207 if (!iconCurrent.equals(iconUpdated)) {
6208 if (!hasBeenCertified) {
6209 Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
6210 if (validateIcon.isRight()) {
6211 ResponseFormat errorResponse = validateIcon.right().value();
6212 return Either.right(errorResponse);
6215 log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
6216 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
6217 return Either.right(errorResponse);
6220 return Either.left(true);
6223 private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6224 String vendorNameUpdated = updateInfoResource.getVendorName();
6225 String vendorNameCurrent = currentResource.getVendorName();
6226 if (!vendorNameCurrent.equals(vendorNameUpdated)) {
6227 if (!hasBeenCertified) {
6228 Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
6229 if (validateVendorName.isRight()) {
6230 ResponseFormat errorResponse = validateVendorName.right().value();
6231 return Either.right(errorResponse);
6234 log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated);
6235 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
6236 return Either.right(errorResponse);
6239 return Either.left(true);
6242 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
6243 String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
6244 String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
6245 if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
6246 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null);
6247 if (validateResourceVendorModelNumber.isRight()) {
6248 ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
6249 return Either.right(errorResponse);
6252 return Either.left(true);
6255 private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
6256 Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
6257 if (validateCategoryName.isRight()) {
6258 ResponseFormat errorResponse = validateCategoryName.right().value();
6259 return Either.right(errorResponse);
6261 if (hasBeenCertified) {
6262 CategoryDefinition currentCategory = currentResource.getCategories().get(0);
6263 SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
6264 CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
6265 SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
6266 if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
6267 log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
6268 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
6269 return Either.right(errorResponse);
6272 return Either.left(true);
6275 private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
6277 List<String> currentDerivedFrom = currentResource.getDerivedFrom();
6278 List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
6279 if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
6280 log.trace("Update normative types");
6281 return Either.left(true);
6284 String derivedFromCurrent = currentDerivedFrom.get(0);
6285 String derivedFromUpdated = updatedDerivedFrom.get(0);
6287 if (!derivedFromCurrent.equals(derivedFromUpdated)) {
6288 if (!hasBeenCertified) {
6289 Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
6290 if (validateDerivedFromExistsEither.isRight()) {
6291 return validateDerivedFromExistsEither;
6294 Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
6296 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
6297 log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
6298 return validateDerivedFromExtending;
6302 // For derived from, we must know whether it was actually changed,
6303 // otherwise we must do no action.
6304 // Due to changes it inflicts on data model (remove artifacts,
6305 // properties...), it's not like a flat field which can be
6306 // overwritten if not changed.
6307 // So we must indicate that derived from is not changed
6308 updateInfoResource.setDerivedFrom(null);
6310 return Either.left(true);
6313 private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
6315 if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
6316 return Either.left(true);
6319 // IResourceOperation resourceOperation = getResourceOperation();
6321 String templateName = resource.getDerivedFrom().get(0);
6323 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
6324 if (dataModelResponse.isRight()) {
6325 StorageOperationStatus storageStatus = dataModelResponse.right().value();
6326 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
6327 log.debug("request to data model failed with error: {}", storageStatus.name());
6328 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
6329 log.trace("audit before sending response");
6330 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6331 return Either.right(responseFormat);
6332 } else if (!dataModelResponse.left().value()) {
6333 log.info("resource template with name: {}, does not exists", templateName);
6334 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
6335 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6337 return Either.right(responseFormat);
6340 return Either.left(true);
6343 // Tal G for extending inheritance US815447
6344 private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
6345 // If updated resource is not deriving, should fail validation
6347 * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6349 // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
6351 * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
6353 String currentTemplateName = currentResource.getDerivedFrom().get(0);
6354 String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
6356 Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
6357 if (dataModelResponse.isRight()) {
6358 StorageOperationStatus storageStatus = dataModelResponse.right().value();
6359 BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
6360 log.debug("request to data model failed with error: {}", storageStatus.name());
6361 ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
6362 log.trace("audit before sending response");
6363 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6364 return Either.right(responseFormat);
6367 if (!dataModelResponse.left().value()) {
6368 log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
6369 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
6370 componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
6372 return Either.right(responseFormat);
6375 return Either.left(true);
6378 public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
6379 log.debug("validate resource derivedFrom field");
6380 if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
6381 log.info("derived from (template) field is missing for the resource");
6382 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
6383 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6385 return Either.right(responseFormat);
6387 return Either.left(true);
6390 private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
6392 Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
6393 if (resourceOperationResponse.isLeft()) {
6394 if (!resourceOperationResponse.left().value()) {
6395 return Either.left(false);
6397 log.debug("resource with name: {}, already exists", resource.getName());
6398 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
6399 return Either.right(errorResponse);
6402 log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
6403 ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
6404 return Either.right(errorResponse);
6408 * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags();
6410 * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value();
6411 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true);
6415 * 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
6416 * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
6417 * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else {
6418 * 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");
6419 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize,
6420 * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); }
6422 * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); }
6425 private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
6427 List<CategoryDefinition> categories = resource.getCategories();
6428 if (categories == null || categories.size() == 0) {
6429 log.debug("Resource category is empty");
6430 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6431 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6432 return Either.right(responseFormat);
6434 if (categories.size() > 1) {
6435 log.debug("Must be only one category for resource");
6436 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
6437 return Either.right(responseFormat);
6439 CategoryDefinition category = categories.get(0);
6440 List<SubCategoryDefinition> subcategories = category.getSubcategories();
6441 if (subcategories == null || subcategories.size() == 0) {
6442 log.debug("Missinig subcategory for resource");
6443 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
6444 return Either.right(responseFormat);
6446 if (subcategories.size() > 1) {
6447 log.debug("Must be only one sub category for resource");
6448 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
6449 return Either.right(responseFormat);
6452 SubCategoryDefinition subcategory = subcategories.get(0);
6454 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
6455 log.debug("Resource category is empty");
6456 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6457 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6458 return Either.right(responseFormat);
6460 if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
6461 log.debug("Resource category is empty");
6462 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
6463 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6464 return Either.right(responseFormat);
6467 Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
6468 if (validateCategory.isRight()) {
6469 ResponseFormat responseFormat = validateCategory.right().value();
6470 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6471 return Either.right(responseFormat);
6474 return Either.left(true);
6477 private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) {
6478 if (category != null && subcategory != null) {
6479 log.debug("validating resource category {} against valid categories list", category);
6480 Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
6481 if (categories.isRight()) {
6482 log.debug("failed to retrive resource categories from Titan");
6483 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
6484 return Either.right(responseFormat);
6486 List<CategoryDefinition> categoryList = categories.left().value();
6487 for (CategoryDefinition cat : categoryList) {
6488 if (cat.getName().equals(category.getName())) {
6489 for (SubCategoryDefinition subcat : cat.getSubcategories()) {
6490 if (subcat.getName().equals(subcategory.getName())) {
6491 return Either.left(true);
6494 log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories());
6495 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6498 log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
6499 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
6501 return Either.left(false);
6504 public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
6505 String vendorRelease = resource.getVendorRelease();
6507 log.debug("validate vendor relese name");
6508 if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
6509 log.info("vendor relese name is missing.");
6510 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
6511 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6512 return Either.right(errorResponse);
6515 Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
6516 if (validateVendorReleaseResponse.isRight()) {
6517 ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
6518 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6520 return validateVendorReleaseResponse;
6523 public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
6524 if (vendorRelease != null) {
6525 if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
6526 log.info("vendor release exceds limit.");
6527 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
6528 return Either.right(errorResponse);
6531 if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
6532 log.info("vendor release is not valid.");
6533 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
6534 return Either.right(errorResponse);
6536 return Either.left(true);
6538 return Either.left(false);
6542 private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
6543 String vendorName = resource.getVendorName();
6544 if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
6545 log.info("vendor name is missing.");
6546 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
6547 componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
6548 return Either.right(errorResponse);
6551 Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
6552 if (validateVendorNameResponse.isRight()) {
6553 ResponseFormat responseFormat = validateVendorNameResponse.right().value();
6554 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6556 return validateVendorNameResponse;
6560 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
6561 String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
6562 Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber);
6563 if (validateResourceVendorModelNumber.isRight()) {
6564 ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
6565 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6567 return validateResourceVendorModelNumber;
6572 private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
6573 if (vendorName != null) {
6574 if (!ValidationUtils.validateVendorNameLength(vendorName)) {
6575 log.info("vendor name exceds limit.");
6576 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
6577 return Either.right(errorResponse);
6580 if (!ValidationUtils.validateVendorName(vendorName)) {
6581 log.info("vendor name is not valid.");
6582 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
6583 return Either.right(errorResponse);
6585 return Either.left(true);
6588 return Either.left(false);
6592 private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
6593 if (resourceVendorModelNumber.equals("")) {
6594 return Either.left(true);
6596 if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
6597 log.info("resource vendor model number exceeds limit.");
6598 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
6599 return Either.right(errorResponse);
6601 // resource vendor model number is currently validated as vendor name
6602 if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
6603 log.info("resource vendor model number is not valid.");
6604 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
6605 return Either.right(errorResponse);
6607 return Either.left(true);
6613 * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
6614 * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
6615 * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6617 * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
6619 * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
6620 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
6622 * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
6623 * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
6625 * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
6626 * Either.left(false); }
6630 * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
6632 * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
6633 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6635 * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
6636 * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
6638 * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
6639 * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6645 * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
6647 * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
6648 * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
6650 * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
6651 * null); } return validateIcon;
6655 * 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.
6656 * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
6657 * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
6662 private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
6663 String cost = resource.getCost();
6666 if (!ValidationUtils.validateCost(cost)) {
6667 log.debug("resource cost is invalid.");
6668 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6669 return Either.right(errorResponse);
6672 return Either.left(true);
6675 private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
6676 log.debug("validate licenseType");
6677 String licenseType = resource.getLicenseType();
6678 if (licenseType != null) {
6679 List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
6680 if (!licenseTypes.contains(licenseType)) {
6681 log.debug("License type {} isn't configured");
6682 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
6683 if (actionEnum != null) {
6684 // In update case, no audit is required
6685 componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
6687 return Either.right(responseFormat);
6690 return Either.left(true);
6693 private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
6694 Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
6695 if (updatedResource.getDerivedFrom() != null) {
6696 log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
6697 log.debug("1. Removing interface artifacts from graph");
6698 // Remove all interface artifacts of resource
6699 String resourceId = updatedResource.getUniqueId();
6700 Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
6702 if (interfaces != null) {
6703 Collection<InterfaceDefinition> values = interfaces.values();
6704 for (InterfaceDefinition interfaceDefinition : values) {
6705 String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
6707 log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
6708 Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
6709 if (operations != null) {
6710 for (Entry<String, Operation> operationEntry : operations.entrySet()) {
6711 Operation operation = operationEntry.getValue();
6712 ArtifactDefinition implementation = operation.getImplementationArtifact();
6713 if (implementation != null) {
6714 String uniqueId = implementation.getUniqueId();
6715 log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
6716 // only thing that transacts and locks here
6717 deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true);
6718 if (deleteArtifactByInterface.isRight()) {
6719 log.debug("Couldn't remove artifact definition with id {}", uniqueId);
6720 if (!inTransaction) {
6721 titanDao.rollback();
6723 return Either.right(deleteArtifactByInterface.right().value());
6726 log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
6730 log.trace("No operations found for interface type {}", interfaceType);
6734 log.debug("2. Removing properties");
6735 Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
6737 if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
6738 log.debug("Failed to remove all properties of resource");
6740 titanDao.rollback();
6741 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
6745 log.debug("Derived from wasn't changed during update");
6750 return Either.left(true);
6754 /**** Auditing *******************/
6756 protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
6757 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
6759 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
6761 return webApplicationContext.getBean(class1);
6764 public ICapabilityTypeOperation getCapabilityTypeOperation() {
6765 return capabilityTypeOperation;
6768 public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
6769 this.capabilityTypeOperation = capabilityTypeOperation;
6772 public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
6773 log.debug("validate resource properties default values");
6774 Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
6775 List<PropertyDefinition> properties = resource.getProperties();
6777 String innerType = null;
6778 if (properties != null) {
6779 for (PropertyDefinition property : properties) {
6780 if (!propertyOperation.isPropertyTypeValid(property)) {
6781 log.info("Invalid type for property");
6782 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
6783 eitherResult = Either.right(responseFormat);
6787 Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
6788 if (allDataTypes.isRight()) {
6789 return Either.right(allDataTypes.right().value());
6792 type = property.getType();
6793 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6794 ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value());
6795 innerType = propertyInnerTypeValid.getLeft();
6796 if (!propertyInnerTypeValid.getRight().booleanValue()) {
6797 log.info("Invalid inner type for property");
6798 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
6799 eitherResult = Either.right(responseFormat);
6804 if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
6805 log.info("Invalid default value for property");
6806 ResponseFormat responseFormat;
6807 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
6808 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
6810 responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
6812 eitherResult = Either.right(responseFormat);
6818 return eitherResult;
6822 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
6823 return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
6827 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
6828 return vfComponentInstanceBusinessLogic;
6831 private String getComponentTypeForResponse(Component component) {
6832 String componentTypeForResponse = "SERVICE";
6833 if (component instanceof Resource) {
6834 componentTypeForResponse = ((Resource) component).getResourceType().name();
6836 return componentTypeForResponse;
6839 private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6841 Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
6842 Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
6844 Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
6845 if (eitherNodesTemlates.isLeft()) {
6846 Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
6848 if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
6849 Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
6850 while (nodesNameValue.hasNext()) {
6851 Entry<String, Object> groupNameValue = nodesNameValue.next();
6853 String groupName = groupNameValue.getKey();
6854 Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue());
6855 if (eitherNode.isRight()) {
6856 String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName();
6857 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6858 return Either.right(eitherNode.right().value());
6860 GroupDefinition groupDefinition = eitherNode.left().value();
6861 groups.put(groupName, groupDefinition);
6870 private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
6872 Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
6873 if (inputs.isRight()) {
6874 String message = "Failed when creating inputs: for resource:" + resource.getName();
6875 BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
6876 Map<String, InputDefinition> resultMap = new HashMap<>();
6877 return Either.left(resultMap);
6881 Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
6886 @SuppressWarnings("unchecked")
6887 private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
6889 GroupDefinition groupInfo = new GroupDefinition();
6890 groupInfo.setName(groupName);
6891 Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
6894 if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
6895 Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
6896 String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
6897 if (!StringUtils.isEmpty(groupType)) {
6898 groupInfo.setType(groupType);
6900 log.debug("The 'type' member is not found under group {}", groupName);
6901 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
6904 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
6905 groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
6908 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
6909 Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
6910 if (members != null) {
6911 if (members instanceof List) {
6912 Map<String, String> membersLoaded = new HashMap<>();
6913 List<?> membersAsList = (List<?>) members;
6914 for (Object member : membersAsList) {
6915 membersLoaded.put(member.toString(), "");
6917 groupInfo.setMembers(membersLoaded);
6919 log.debug("The 'members' member is not of type list under group {}", groupName);
6920 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6925 if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
6926 Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
6928 Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType);
6929 if (regResponse.isRight())
6930 return Either.right(regResponse.right().value());
6931 if (regResponse.left().value().size() > 0) {
6932 groupInfo.convertFromGroupProperties(regResponse.left().value());
6937 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
6939 } catch (Exception e) {
6940 BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
6941 log.debug("error when creating group, message:{}", e.getMessage(), e);
6942 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
6948 @SuppressWarnings("unchecked")
6949 private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) {
6951 List<GroupProperty> result = new ArrayList<>();
6953 if (properties == null) {
6954 return Either.left(result);
6957 Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
6959 if (groupTypeRes.isRight()) {
6960 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
6963 Map<String, PropertyDefinition> gtProperties = new HashMap<>();
6964 GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
6966 List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
6968 if (propertiesDef != null) {
6969 gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
6972 if (properties != null) {
6974 if (properties instanceof Map) {
6976 Map<String, Object> props = (Map<String, Object>) properties;
6977 for (Entry<String, Object> entry : props.entrySet()) {
6979 String propName = entry.getKey();
6980 Object value = entry.getValue();
6982 PropertyDefinition gtDefinition = gtProperties.get(propName);
6983 if (gtDefinition == null) {
6984 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType));
6987 ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
6989 String convertedValue = null;
6990 if (value != null) {
6991 if (type == null || value instanceof Map || value instanceof List) {
6992 convertedValue = gson.toJson(value);
6994 convertedValue = value.toString();
6998 GroupProperty groupProperty = new GroupProperty();
6999 groupProperty.setValue(convertedValue);
7000 groupProperty.setName(propName);
7002 log.trace("After building group property {}", groupProperty);
7004 result.add(groupProperty);
7011 return Either.left(result);
7014 public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
7018 Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false);
7019 if (userValidation.isRight()) {
7020 return Either.right(userValidation.right().value());
7024 // get resource from csar uuid
7025 Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
7026 if (either.isRight()) {
7027 ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
7028 return Either.right(resp);
7031 return Either.left(either.left().value());
7035 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
7039 private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
7040 ResponseFormat responseFormat;
7041 Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
7043 for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
7044 String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
7045 if (!defaultCapabilities.containsKey(capabilityType)) {
7046 responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
7047 return Either.right(responseFormat);
7049 CapabilityDefinition defaultCapability;
7050 if(CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())){
7051 defaultCapability = defaultCapabilities.get(capabilityType).get(0);
7053 Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
7054 if(getFullComponentRes.isRight()){
7055 log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
7056 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
7057 return Either.right(responseFormat);
7059 defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
7061 if(CollectionUtils.isEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){
7062 log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
7063 log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
7064 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
7065 return Either.right(responseFormat);
7067 if(CollectionUtils.isNotEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){
7068 Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
7069 if (validationRes.isRight()) {
7070 responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value());
7071 return Either.right(responseFormat);
7074 List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
7075 validCapabilityList.add(defaultCapability);
7076 validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
7079 return Either.left(validCapabilitiesMap);
7082 private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
7083 List<ComponentInstanceProperty> validProperties = new ArrayList<>();
7084 Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
7085 List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
7086 for (UploadPropInfo property : uploadedProperties) {
7087 String propertyName = property.getName().toLowerCase();
7088 String propertyType = property.getType();
7089 ComponentInstanceProperty validProperty;
7090 if (defaultProperties.containsKey(propertyName)) {
7091 if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
7092 return Either.right(propertyName);
7095 validProperty = new ComponentInstanceProperty();
7096 validProperty.setName(propertyName);
7097 if (property.getValue() != null)
7098 validProperty.setValue(property.getValue().toString());
7099 validProperty.setDescription(property.getDescription());
7100 validProperty.setPassword(property.isPassword());
7101 validProperties.add(validProperty);
7103 defaultCapability.setProperties(validProperties);
7104 return Either.left(true);
7107 private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
7108 Resource resource, User user) {
7110 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
7111 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
7112 Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
7115 // add all found Csar artifacts to list to upload
7116 List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
7117 List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
7118 List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
7119 for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
7120 ArtifactDefinition foundArtifact;
7122 if (!existingArtifactsToHandle.isEmpty()) {
7123 foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
7124 if (foundArtifact != null) {
7125 if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
7126 if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
7127 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
7128 // if current artifact already exists, but has different content, add him to the list to update
7129 artifactsToUpdate.add(currNewArtifact);
7131 // remove found artifact from the list of existing artifacts to handle, because it was already handled
7132 existingArtifactsToHandle.remove(foundArtifact);
7133 // and remove found artifact from the list to upload, because it should either be updated or be ignored
7134 artifactsToUpload.remove(currNewArtifact);
7136 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
7137 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
7138 currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
7139 AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
7140 artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
7141 responseWrapper.setInnerElement(responseFormat);
7147 if (responseWrapper.isEmpty()) {
7148 existingArtifactsToHandle.stream()
7149 // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
7150 .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
7152 if (responseWrapper.isEmpty()) {
7153 if (!artifactsToUpload.isEmpty())
7154 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
7155 if (!artifactsToUpdate.isEmpty())
7156 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
7157 if (!artifactsToDelete.isEmpty())
7158 nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
7160 if (!responseWrapper.isEmpty()) {
7161 nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
7163 } catch (Exception e) {
7164 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
7165 responseWrapper.setInnerElement(responseFormat);
7166 log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
7168 return nodeTypeArtifactsToHandleRes;
7172 private String buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
7174 String actualVfName;
7175 if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){
7176 actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
7177 actualType = ResourceTypeEnum.VFC.name();
7179 actualVfName = vfResourceName;
7180 actualType = nodeResourceType;
7182 StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
7183 String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
7184 String[] findTypes = nameWithouNamespacePrefix.split("\\.");
7185 String resourceType = findTypes[0];
7186 String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
7188 if (actualName.startsWith(Constants.ABSTRACT)) {
7189 toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
7191 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
7193 return toscaResourceName.append(actualName.toLowerCase()).toString();
7196 public ICacheMangerOperation getCacheManagerOperation() {
7197 return cacheManagerOperation;
7200 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
7201 this.cacheManagerOperation = cacheManagerOperation;
7204 ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
7206 public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
7208 ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
7209 Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
7211 if (resourceResultEither.isRight()) {
7212 if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
7213 log.debug("Failed to found resource with id {} ", resourceId);
7214 Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
7217 log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn.toString());
7218 return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
7221 Resource resource = resourceResultEither.left().value();
7222 UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
7223 return Either.left(dataTransfer);