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 com.google.common.annotations.VisibleForTesting;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import fj.data.Either;
27 import org.apache.commons.codec.binary.Base64;
28 import org.apache.commons.collections.CollectionUtils;
29 import org.apache.commons.collections.MapUtils;
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.elasticsearch.common.Strings;
33 import org.openecomp.sdc.be.components.ArtifactsResolver;
34 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
35 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
36 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
37 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager;
40 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
41 import org.openecomp.sdc.be.config.ConfigurationManager;
42 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
43 import org.openecomp.sdc.be.dao.api.ActionStatus;
44 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
45 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
46 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
47 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
51 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
52 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
53 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
54 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
55 import org.openecomp.sdc.be.model.*;
56 import org.openecomp.sdc.be.model.heat.HeatParameterType;
57 import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
58 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
59 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
60 import org.openecomp.sdc.be.model.operations.api.*;
61 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
62 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
63 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
64 import org.openecomp.sdc.be.resources.data.ESArtifactData;
65 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
66 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
67 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
68 import org.openecomp.sdc.be.servlets.RepresentationUtils;
69 import org.openecomp.sdc.be.tosca.CsarUtils;
70 import org.openecomp.sdc.be.tosca.ToscaError;
71 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
72 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
73 import org.openecomp.sdc.be.user.IUserBusinessLogic;
74 import org.openecomp.sdc.be.user.Role;
75 import org.openecomp.sdc.be.user.UserBusinessLogic;
76 import org.openecomp.sdc.be.utils.TypeUtils;
77 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
78 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
79 import org.openecomp.sdc.common.api.Constants;
80 import org.openecomp.sdc.common.datastructure.Wrapper;
81 import org.openecomp.sdc.common.log.wrappers.Logger;
82 import org.openecomp.sdc.common.util.GeneralUtility;
83 import org.openecomp.sdc.common.util.ValidationUtils;
84 import org.openecomp.sdc.common.util.YamlToObjectConverter;
85 import org.openecomp.sdc.exception.ResponseFormat;
87 import org.springframework.beans.factory.annotation.Autowired;
89 import org.yaml.snakeyaml.Yaml;
91 import javax.servlet.http.HttpServletRequest;
92 import javax.xml.XMLConstants;
93 import javax.xml.parsers.ParserConfigurationException;
94 import javax.xml.parsers.SAXParserFactory;
95 import java.io.ByteArrayInputStream;
96 import java.io.IOException;
97 import java.math.BigDecimal;
99 import java.util.Map.Entry;
100 import java.util.function.Predicate;
101 import java.util.function.Supplier;
102 import java.util.stream.Collectors;
104 @org.springframework.stereotype.Component("artifactBusinessLogic")
105 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
106 private static final String RESOURCE_INSTANCE = "resource instance";
107 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
108 private static final String ARTIFACT_DESCRIPTION = "artifact description";
109 private static final String ARTIFACT_LABEL = "artifact label";
110 private static final String ARTIFACT_URL = "artifact url";
111 private static final String ARTIFACT_NAME = "artifact name";
112 private static final String ARTIFACT_PAYLOAD = "artifact payload";
114 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
115 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
116 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
118 public static final String HEAT_ENV_NAME = "heatEnv";
119 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
120 public static final String HEAT_ENV_SUFFIX = "env";
121 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
123 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
124 public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
125 public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
126 public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
127 public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
128 public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
129 public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
130 public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
131 public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
132 public static final String NULL_PARAMETER = "One of the function parameteres is null";
133 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
134 public static final String ROLLBACK = "all changes rollback";
135 public static final String COMMIT = "all changes committed";
136 public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
137 public static final String UPDATE_ARTIFACT = "Update Artifact";
138 public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
139 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
141 @javax.annotation.Resource
142 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
143 @javax.annotation.Resource
144 private IUserAdminOperation userOperaton;
146 @javax.annotation.Resource
147 private IElementOperation elementOperation;
149 @javax.annotation.Resource
150 private ResourceBusinessLogic resourceBusinessLogic;
152 @javax.annotation.Resource
153 private ServiceBusinessLogic serviceBusinessLogic;
155 @javax.annotation.Resource
156 private UserBusinessLogic userAdminManager;
158 @javax.annotation.Resource
159 private IHeatParametersOperation heatParametersOperation;
162 private ArtifactCassandraDao artifactCassandraDao;
165 private ToscaExportHandler toscaExportUtils;
168 private CsarUtils csarUtils;
171 private LifecycleBusinessLogic lifecycleBusinessLogic;
174 private IUserBusinessLogic userBusinessLogic;
177 private NodeTemplateOperation nodeTemplateOperation;
180 private ArtifactsResolver artifactsResolver;
182 public enum ArtifactOperationEnum {
183 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
185 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
186 return operation == CREATE || operation == LINK;
190 public class ArtifactOperationInfo {
192 private ArtifactOperationEnum artifactOperationEnum;
193 private boolean isExternalApi;
194 private boolean ignoreLifecycleState;
196 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
197 this.artifactOperationEnum = artifactOperationEnum;
198 this.isExternalApi = isExternalApi;
199 this.ignoreLifecycleState = ignoreLifecycleState;
202 public boolean isExternalApi() {
203 return isExternalApi;
206 public boolean ignoreLifecycleState() {
207 return ignoreLifecycleState;
210 public ArtifactOperationEnum getArtifactOperationEnum() {
211 return artifactOperationEnum;
217 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
218 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
219 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
222 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
223 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
225 // step 1 - detect auditing type
226 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
227 // step 2 - check header
228 if (userId == null) {
229 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
230 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
231 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
232 return Either.right(responseFormat);
234 // step 3 - check user existence
235 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
236 if (userResult.isRight()) {
237 return Either.right(userResult.right().value());
240 // step 4 - check user's role
241 User user = userResult.left().value();
242 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
243 if (validateUserRole.isRight()) {
244 return Either.right(validateUserRole.right().value());
248 // 5. check service/resource existence
249 // 6. check service/resource check out
250 // 7. user is owner of checkout state
251 org.openecomp.sdc.be.model.Component component = null;
252 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
253 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
254 if (validateComponent.isRight()) {
255 return Either.right(validateComponent.right().value());
257 component = validateComponent.left().value();
258 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
259 if (validateWorkOnResource.isRight()) {
260 return Either.right(validateWorkOnResource.right().value());
264 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
265 shouldLock, inTransaction, true);
269 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
270 * For regular usage use <br>
271 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
275 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
276 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
277 Component parent = component;
278 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
280 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
281 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
283 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
284 if (errorWrapper.isEmpty()) {
286 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
289 result = Either.right(errorWrapper.getInnerElement());
294 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
295 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
296 ArtifactDefinition validatedArtifactInfo = artifactInfo;
297 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
298 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
299 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
300 if (validateArtifact.isRight()) {
301 ResponseFormat responseFormat = validateArtifact.right().value();
302 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
303 errorWrapper.setInnerElement(validateArtifact.right().value());
305 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
306 validatedArtifactInfo = validateArtifact.left().value();
307 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
310 return validatedArtifactInfo;
313 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
314 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
315 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
317 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
318 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
319 ComponentInstance componentInstance = component.getComponentInstances()
321 .filter(p -> p.getUniqueId().equals(componentId))
324 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
326 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
328 .filter(p -> p.getUniqueId()
329 .equals(validatedArtifact.getUniqueId()))
332 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
333 .getName(), user, componentId, shouldLock, inTransaction);
334 if (eitherGenerated.isRight()) {
335 errorWrapper.setInnerElement(eitherGenerated.right().value());
340 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
341 boolean needGenerate;
342 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
343 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
344 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
345 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
346 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
350 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
351 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
353 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
356 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
357 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
359 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
360 if (generated.isRight()) {
363 byte[] decodedPayload = artifactDefinition.getPayloadData();
364 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
365 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
366 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
367 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
368 shouldLock, inTransaction);
372 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
373 log.debug("tosca artifact generation");
374 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
375 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
377 if (generated.isRight()) {
378 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
381 return Either.right(generated.right().value());
383 byte[] value = generated.left().value();
384 artifactInfo.setPayload(value);
388 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
389 if (exportComponent.isRight()) {
390 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
392 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
393 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
394 return Either.right(responseFormat);
396 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
397 String payload = exportComponent.left().value().getMainYaml();
398 artifactInfo.setPayloadData(payload);
400 return Either.left(Either.left(artifactInfo));
403 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
404 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
405 switch (operation.getArtifactOperationEnum()) {
407 if (artifactGenerationRequired(parent, artifactInfo)) {
408 return generateNotSavedArtifact(parent, artifactInfo);
410 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
412 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
414 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
415 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
416 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
417 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
418 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
419 if (needUpdateGroup && result.isLeft()) {
420 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
421 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
422 .value(), parent, componentType, componentId);
423 if (error != ActionStatus.OK) {
424 result = Either.right(componentsUtils.getResponseFormat(error));
429 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
430 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
433 if (result == null) {
434 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
435 if (needUpdateGroup && result.isLeft()) {
436 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
438 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
439 .value(), parent, componentType);
440 if (error != ActionStatus.OK) {
441 result = Either.right(componentsUtils.getResponseFormat(error));
447 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
449 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
454 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
455 List<GroupDefinition> groups = parent.getGroups();
456 if (groups != null && !groups.isEmpty()) {
457 List<GroupDataDefinition> groupToUpdate = groups.stream()
458 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
459 .contains(artifactInfo
461 .collect(Collectors.toList());
462 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
463 groupToUpdate.forEach(g -> {
464 g.getArtifacts().remove(artifactInfo.getUniqueId());
465 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
466 g.getArtifacts().add(artAfterUpdate.getUniqueId());
467 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
469 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
470 if (status.isRight()) {
471 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
472 return componentsUtils.convertFromStorageResponse(status.right().value());
476 return ActionStatus.OK;
479 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
480 List<GroupDefinition> groups = parent.getGroups();
481 if (groups != null && !groups.isEmpty()) {
482 List<GroupDataDefinition> groupToUpdate = groups.stream()
483 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
484 .contains(artifactInfoHeat
486 .collect(Collectors.toList());
487 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
488 groupToUpdate.forEach(g -> {
489 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
490 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
491 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
492 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
493 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
494 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
496 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
497 if (status.isRight()) {
498 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
499 return componentsUtils.convertFromStorageResponse(status.right().value());
503 return ActionStatus.OK;
506 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
507 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
508 List<GroupInstance> groupInstances = null;
509 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
511 .filter(ci -> ci.getUniqueId().equals(parentId))
513 if (componentInstOp.isPresent()) {
514 groupInstances = componentInstOp.get().getGroupInstances();
516 if (CollectionUtils.isNotEmpty(groupInstances)) {
517 boolean isUpdated = false;
518 for (GroupInstance groupInstance : groupInstances) {
520 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
521 .contains(artifactInfo
523 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
524 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
527 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
528 .contains(artifactInfo
529 .getArtifactUUID())) {
530 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
531 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
535 updatedGroupInstances.add(groupInstance);
539 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
540 if (status.isRight()) {
541 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
542 return componentsUtils.convertFromStorageResponse(status.right().value());
544 return ActionStatus.OK;
547 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
548 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
549 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
550 result = generateToscaArtifact(parent, artifactInfo, false, false);
553 String heatArtifactId = artifactInfo.getGeneratedFromId();
554 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
555 if (heatRes.isRight()) {
556 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
558 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
561 return Either.right(responseFormat);
563 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
564 artifactInfo.setPayloadData(generatedPayload);
565 result = Either.left(Either.left(artifactInfo));
570 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
571 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
572 convertParentType(componentType);
573 String parentId = parent.getUniqueId();
574 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
575 .getGeneratedFromId());
576 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
578 if (origMd5 != null) {
579 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
580 if (validateMd5.isRight()) {
581 ResponseFormat responseFormat = validateMd5.right().value();
582 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
583 return Either.right(responseFormat);
586 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
588 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
589 if (payloadEither.isRight()) {
590 ResponseFormat responseFormat = payloadEither.right().value();
591 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
592 return Either.right(responseFormat);
596 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
597 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
598 return Either.right(responseFormat);
604 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
605 if (lockComponent.isRight()) {
606 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
607 .value(), componentType, null);
608 return Either.right(lockComponent.right().value());
611 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
613 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
619 if (resultOp == null || resultOp.isRight()) {
621 if (!inTransaction) {
627 if (!inTransaction) {
632 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
637 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
638 if (artifactGenerationRequired(component, csarArtifact)) {
639 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
641 if (generated.isRight()) {
642 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
645 return Either.right(generated.right().value());
647 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
650 return downloadArtifact(csarArtifact);
653 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
654 // perform all validation in common flow
655 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
656 null, parentId, containerComponentType);
657 if (result.isRight()) {
658 return Either.right(result.right().value());
660 ArtifactDefinition artifactDefinition;
661 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
662 if (insideValue.isLeft()) {
663 artifactDefinition = insideValue.left().value();
666 artifactDefinition = insideValue.right().value().getImplementationArtifact();
668 // for tosca artifacts and heat env on VF level generated on download without saving
669 if (artifactDefinition.getPayloadData() != null) {
670 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
673 return downloadArtifact(artifactDefinition);
676 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
678 // detect auditing type
679 Map<String, ArtifactDefinition> resMap = null;
680 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
685 if (userId == null) {
686 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
687 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
689 resultOp = Either.right(responseFormat);
693 // check user existence
697 validateUserExists(userId, "get artifacts", false);
699 // 5. check service/resource existence
700 // 6. check service/resource check out
701 // 7. user is owner of checkout state
702 org.openecomp.sdc.be.model.Component component = null;
703 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
704 ComponentParametersView componentFilter = new ComponentParametersView();
705 componentFilter.disableAll();
706 componentFilter.setIgnoreArtifacts(false);
707 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
708 componentFilter.setIgnoreComponentInstances(false);
711 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
712 .findByParamName(containerComponentType), componentFilter);
714 if (validateComponent.isRight()) {
715 resultOp = Either.right(validateComponent.right().value());
718 component = validateComponent.left().value();
719 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
720 if (lockComponent.isRight()) {
722 resultOp = Either.right(lockComponent.right().value());
727 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
729 if (groupType == null) {
730 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
731 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
733 resultOp = Either.right(responseFormat);
737 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
738 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
739 if (list != null && !list.isEmpty()) {
740 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
743 resMap = new HashMap<>();
745 resultOp = Either.left(resMap);
750 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
751 .getNodeType(), groupType, componentId);
752 if (artifactsMapStatus.isRight()) {
753 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
754 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
755 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
756 resultOp = Either.right(responseFormat);
759 resMap = new HashMap<>();
760 resultOp = Either.left(resMap);
764 resMap = artifactsMapStatus.left().value();
765 resultOp = Either.left(resMap);
772 if (resultOp == null || resultOp.isRight()) {
781 componentType = component.getComponentType();
782 NodeTypeEnum nodeType = componentType.getNodeType();
783 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
788 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
790 // check artifact existence
791 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
793 if (artifactResult.isRight()) {
794 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
795 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
796 log.debug("addArtifact - artifact {} not found", artifactId);
797 return Either.right(responseFormat);
801 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
804 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
806 return Either.right(responseFormat);
810 // check artifact belong to component
811 boolean found = false;
812 switch (componentType) {
815 found = checkArtifactInComponent(component, artifactId);
817 case RESOURCE_INSTANCE:
818 found = checkArtifactInResourceInstance(component, componentId, artifactId);
824 String componentName = componentType.name().toLowerCase();
825 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
826 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
827 return Either.right(responseFormat);
829 return Either.left(artifactResult.left().value());
832 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
833 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
835 String artifactId = null;
838 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
839 if (payloadEither.isRight()) {
840 return Either.right(payloadEither.right().value());
842 byte[] decodedPayload = payloadEither.left().value();
843 convertParentType(componentType);
846 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
847 if (lockComponent.isRight()) {
848 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
849 .value(), componentType, null);
850 return Either.right(lockComponent.right().value());
853 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
856 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
861 unlockComponent(resultOp, parent, inTransaction);
868 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
869 Component parent, boolean shouldLock, boolean inTransaction) {
872 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
873 if (lockComponent.isRight()) {
874 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
875 .value(), componentType, null);
876 return Either.right(lockComponent.right().value());
879 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
882 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
887 unlockComponent(resultOp, parent, inTransaction);
894 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
895 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
897 convertParentType(componentType);
901 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
903 if (lockComponent.isRight()) {
904 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
905 .value(), componentType, null);
906 return Either.right(lockComponent.right().value());
910 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
912 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
918 unlockComponent(resultOp, parent, inTransaction);
923 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
924 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
926 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
928 if (payloadEither.isRight()) {
929 return Either.right(payloadEither.right().value());
931 byte[] decodedPayload = payloadEither.left().value();
933 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
936 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
937 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
939 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
940 if (validateMd5.isRight()) {
941 ResponseFormat responseFormat = validateMd5.right().value();
942 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
943 return Either.right(responseFormat);
947 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
948 if (validateResult.isRight()) {
949 ResponseFormat responseFormat = validateResult.right().value();
950 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
951 return Either.right(validateResult.right().value());
954 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
955 if (payloadEither.isRight()) {
956 ResponseFormat responseFormat = payloadEither.right().value();
957 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
958 log.debug("Error during handle payload");
959 return Either.right(responseFormat);
962 // validate heat parameters. this part must be after the parameters are
963 // extracted in "handlePayload"
964 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
966 if (validateAndConvertHeatParamers.isRight()) {
967 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
968 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
969 log.debug("Error during handle payload");
970 return Either.right(responseFormat);
972 return payloadEither;
975 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
976 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
978 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
984 user.setUserId("UNKNOWN");
986 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
989 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
990 switch (componentTypeEnum) {
992 Resource resource = (Resource) component;
993 if (resource == null) {
994 // In that case, component ID should be instead of name
995 resource = new Resource();
996 resource.setName(componentId);
998 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
999 ResourceVersionInfo.newBuilder()
1000 .artifactUuid(prevArtifactUuid)
1001 .build(), currentArtifactUuid, artifactDefinition);
1005 Service service = (Service) component;
1006 if (service == null) {
1007 // In that case, component ID should be instead of name
1008 service = new Service();
1009 service.setName(componentId);
1011 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1012 ResourceVersionInfo.newBuilder()
1013 .artifactUuid(prevArtifactUuid)
1015 ResourceVersionInfo.newBuilder()
1016 .artifactUuid(currentArtifactUuid)
1018 null, artifactDefinition, null);
1021 case RESOURCE_INSTANCE:
1022 if (resourceInstanceName == null) {
1023 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1025 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1026 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1027 ResourceVersionInfo.newBuilder()
1028 .artifactUuid(prevArtifactUuid)
1030 ResourceVersionInfo.newBuilder()
1031 .artifactUuid(currentArtifactUuid)
1033 null, artifactDefinition, null);
1040 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1041 ComponentInstance resourceInstance = component.getComponentInstances()
1043 .filter(p -> p.getUniqueId().equals(componentId))
1046 String resourceInstanceName = null;
1047 if (resourceInstance != null) {
1048 resourceInstanceName = resourceInstance.getName();
1050 return resourceInstanceName;
1053 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1054 StringBuilder sb = new StringBuilder();
1055 if (artifactDefinition != null) {
1056 sb.append(artifactDefinition.getArtifactGroupType().getType())
1059 .append(artifactDefinition.getArtifactLabel())
1062 .append(artifactDefinition.getArtifactType())
1064 .append(artifactDefinition.getArtifactName())
1066 .append(artifactDefinition.getTimeout())
1068 .append(artifactDefinition.getEsId());
1071 if (artifactDefinition.getArtifactVersion() != null) {
1073 sb.append(artifactDefinition.getArtifactVersion());
1079 if (artifactDefinition.getArtifactUUID() != null) {
1080 sb.append(artifactDefinition.getArtifactUUID());
1086 return sb.toString();
1089 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1091 if (origMd5 != null) {
1092 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1093 if (!encodeBase64Str.equals(origMd5)) {
1094 log.debug("The calculated md5 is different then the received one");
1095 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1099 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1100 log.debug("Missing md5 header during artifact create");
1101 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1104 if (payload != null && payload.length != 0) {
1105 log.debug("Cannot have payload while md5 header is missing");
1106 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1109 return Either.left(true);
1112 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1113 ComponentTypeEnum componentType, Component parentComponent) {
1115 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1116 if (artifactById.isRight()) {
1117 return Either.right(artifactById.right().value());
1119 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1121 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1122 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1123 if (validateInformationalArtifactRes.isRight()) {
1124 return Either.right(validateInformationalArtifactRes.right().value());
1126 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1127 if (validateAndSetArtifactname.isRight()) {
1128 return Either.right(validateAndSetArtifactname.right().value());
1130 if (operationName != null && interfaceName != null) {
1131 operationName = operationName.toLowerCase();
1132 interfaceName = interfaceName.toLowerCase();
1134 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1135 if (logicalNameStatus.isRight()) {
1136 return Either.right(logicalNameStatus.right().value());
1138 // This is a patch to block possibility of updating service api fields
1139 // through other artifacts flow
1141 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1142 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1143 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1146 checkCreateFields(user, artifactInfo, artifactGroupType);
1149 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1150 if (currentArtifactInfo != null) {
1151 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1154 // artifactGroupType is not allowed to be updated
1155 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1156 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1157 if (validateGroupType.isRight()) {
1158 return Either.right(validateGroupType.right().value());
1161 NodeTypeEnum parentType = convertParentType(componentType);
1163 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1165 if (isDeploymentArtifact(artifactInfo)) {
1166 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1167 if (deploymentValidationResult.isRight()) {
1168 return Either.right(deploymentValidationResult.right().value());
1172 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1175 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1176 if (descriptionResult.isRight()) {
1177 return Either.right(descriptionResult.right().value());
1180 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1181 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1182 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1183 if (validateServiceApiType.isRight()) {
1184 return Either.right(validateServiceApiType.right().value());
1186 // Change of type is not allowed and should be ignored
1188 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1190 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1191 if (validateUrl.isRight()) {
1192 return Either.right(validateUrl.right().value());
1195 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1196 if (validateUpdate.isRight()) {
1197 log.debug("serviceApi first update cnnot be without payload.");
1198 return Either.right(validateUpdate.right().value());
1202 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1203 if (validateArtifactType.isRight()) {
1204 return Either.right(validateArtifactType.right().value());
1206 if (artifactInfo.getApiUrl() != null) {
1207 artifactInfo.setApiUrl(null);
1208 log.error("Artifact URL cannot be set through this API - ignoring");
1211 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1212 artifactInfo.setServiceApi(false);
1213 log.error("Artifact service API flag cannot be changed - ignoring");
1217 return Either.left(artifactInfo);
1220 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1221 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1222 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1223 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1224 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1228 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1230 Either<ArtifactDefinition, ResponseFormat> result = null;
1231 ArtifactDefinition foundArtifact = null;
1232 if (StringUtils.isNotEmpty(artifactId)) {
1233 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1235 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1236 log.debug("Artifact {} already exist", artifactId);
1237 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1239 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1240 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1241 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1243 if (result == null) {
1244 result = Either.left(foundArtifact);
1249 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1250 ArtifactDefinition foundArtifact;
1251 if (parentComponent.getUniqueId().equals(parentId)) {
1252 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1255 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1256 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1258 return foundArtifact;
1261 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1262 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1263 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1264 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1265 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1266 if (artifactType == null) {
1267 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1268 .getArtifactType()));
1270 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1271 String artifactTypeName = artifactType.getType();
1272 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1273 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1275 .getResourceInformationalArtifacts();
1276 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1277 if (!validArtifactTypes.contains(artifactTypeName)) {
1278 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1281 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1282 .getValidForResourceTypes();
1283 if (!validResourceType.contains(parentResourceType.name())) {
1284 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1288 return validationResult;
1291 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1292 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1293 return NodeTypeEnum.Resource;
1295 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1296 return NodeTypeEnum.ResourceInstance;
1299 return NodeTypeEnum.Service;
1303 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1304 boolean shouldLock, boolean inTransaction) {
1306 NodeTypeEnum parentType = convertParentType(componentType);
1307 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1308 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1309 ArtifactDefinition foundArtifact = null;
1310 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1311 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1312 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1313 boolean isDuplicated = false;
1315 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1318 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1319 if (lockComponent.isRight()) {
1320 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1321 .value(), componentType, null);
1322 resultOp = Either.right(lockComponent.right().value());
1325 if (resultOp == null) {
1326 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1327 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1328 if (getContainerRes.isRight()) {
1329 log.debug("Failed to fetch the container component {}. ", parentId);
1330 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1332 .value()), artifactId);
1333 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1334 resultOp = Either.right(responseFormat);
1337 if (resultOp == null) {
1338 fetchedContainerComponent = getContainerRes.left().value();
1339 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1340 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1341 if (getArtifactRes.isRight()) {
1342 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1344 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1345 .value(), artifactId);
1346 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1347 resultOp = Either.right(responseFormat);
1350 foundArtifact = getArtifactRes.left().value().getLeft();
1351 esId = foundArtifact.getEsId();
1354 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1355 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1356 .getComponentType()));
1357 if (needCloneRes.isRight()) {
1358 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1359 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1361 .value()), foundArtifact.getArtifactDisplayName());
1362 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1363 resultOp = Either.right(responseFormat);
1366 boolean isNeedToDeleteArtifactFromDB = true;
1367 if (resultOp == null) {
1369 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1370 String instanceId = parentId;
1371 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1373 if (isOnlyResourceInstanceArtifact.isRight()) {
1374 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1375 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1376 .value(), foundArtifact
1377 .getArtifactDisplayName());
1378 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1379 return Either.right(responseFormat);
1381 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1384 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1387 if (updatedArtifactRes.isRight()) {
1388 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1389 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1391 .value()), foundArtifact.getArtifactDisplayName());
1392 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1393 resultOp = Either.right(responseFormat);
1396 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1400 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1401 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1402 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1403 if (cassandraStatus != CassandraOperationStatus.OK) {
1404 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1405 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1406 .getArtifactDisplayName());
1407 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1408 resultOp = Either.right(responseFormat);
1411 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1413 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1417 .getGroupInstances());
1418 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1419 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1420 if (status.isRight()) {
1421 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1422 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1424 .value()), foundArtifact.getArtifactDisplayName());
1425 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1426 resultOp = Either.right(responseFormat);
1430 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1431 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1432 if (status != StorageOperationStatus.OK) {
1433 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1434 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1435 .getArtifactDisplayName());
1436 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1437 resultOp = Either.right(responseFormat);
1440 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1441 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1443 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1444 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1445 if (status.isRight()) {
1446 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1447 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1449 .value()), foundArtifact.getArtifactDisplayName());
1450 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1451 resultOp = Either.right(responseFormat);
1455 if (resultOp == null) {
1456 resultOp = Either.left(Either.left(foundArtifact));
1457 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1463 unlockComponent(resultOp, parent, inTransaction);
1468 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1469 Either<Boolean, ActionStatus> result = Either.left(true);
1470 ComponentInstance foundInstance = null;
1471 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1473 .filter(i -> i.getUniqueId().equals(instanceId))
1475 if (!componentInstanceOpt.isPresent()) {
1476 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1479 foundInstance = componentInstanceOpt.get();
1480 String componentUid = foundInstance.getComponentUid();
1481 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1482 if (getContainerRes.isRight()) {
1483 log.debug("Failed to fetch the container component {}. ", componentUid);
1484 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1486 Component origComponent = getContainerRes.left().value();
1487 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1488 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1489 Optional<String> op = deploymentArtifacts.keySet()
1491 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1493 if (op.isPresent()) {
1494 return Either.left(false);
1497 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1498 if (artifacts != null && !artifacts.isEmpty()) {
1499 Optional<String> op = artifacts.keySet()
1501 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1503 if (op.isPresent()) {
1504 return Either.left(false);
1512 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1513 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1514 boolean isUpdated = false;
1515 if (groups != null) {
1516 for (GroupDefinition group : groups) {
1518 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1519 group.getArtifacts().remove(artifactId);
1522 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1523 .contains(foundArtifact.getArtifactUUID())) {
1524 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1528 updatedGroups.add(group);
1532 return updatedGroups;
1535 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1536 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1537 if (CollectionUtils.isNotEmpty(groupInstances)) {
1538 boolean isUpdated = false;
1539 for (GroupInstance groupInstance : groupInstances) {
1541 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1542 .contains(artifactId)) {
1543 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1546 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1547 .contains(foundArtifact
1548 .getArtifactUUID())) {
1549 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1553 updatedGroupInstances.add(groupInstance);
1557 return updatedGroupInstances;
1560 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1562 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1563 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1564 String componentId = component.getUniqueId();
1565 String instanceId = componentId.equals(parentId) ? null : parentId;
1567 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1568 resetMandatoryArtifactFields(foundArtifact);
1569 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1571 else if (cloneIsNeeded) {
1572 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1573 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1576 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1577 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1582 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1584 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1585 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1586 ComponentInstance foundInstance = null;
1587 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1588 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1590 .filter(i -> i.getUniqueId()
1593 if (!componentInstanceOpt.isPresent()) {
1594 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1597 foundInstance = componentInstanceOpt.get();
1598 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1602 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1604 if (result == null) {
1605 if (artifacts.containsKey(artifactId)) {
1606 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1609 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1615 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1616 Map<String, ArtifactDefinition> currArtifacts;
1617 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1618 currArtifacts = component.getDeploymentArtifacts()
1621 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1622 if (MapUtils.isNotEmpty(currArtifacts)) {
1623 artifacts.putAll(currArtifacts);
1626 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1627 currArtifacts = component.getArtifacts()
1630 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1631 if (MapUtils.isNotEmpty(currArtifacts)) {
1632 artifacts.putAll(currArtifacts);
1635 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1636 currArtifacts = component.getToscaArtifacts()
1639 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1640 if (MapUtils.isNotEmpty(currArtifacts)) {
1641 artifacts.putAll(currArtifacts);
1646 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1647 Map<String, ArtifactDefinition> currArtifacts;
1648 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1649 currArtifacts = instance.getDeploymentArtifacts()
1652 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1653 if (MapUtils.isNotEmpty(currArtifacts)) {
1654 artifacts.putAll(currArtifacts);
1657 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1658 currArtifacts = instance.getArtifacts()
1661 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1662 if (MapUtils.isNotEmpty(currArtifacts)) {
1663 artifacts.putAll(currArtifacts);
1668 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1669 if (fetchedArtifact != null) {
1670 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1671 fetchedArtifact.setEsId(null);
1672 fetchedArtifact.setArtifactName(null);
1673 fetchedArtifact.setDescription(null);
1674 fetchedArtifact.setApiUrl(null);
1675 fetchedArtifact.setArtifactChecksum(null);
1676 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1677 fetchedArtifact.setArtifactUUID(null);
1678 long time = System.currentTimeMillis();
1679 fetchedArtifact.setPayloadUpdateDate(time);
1680 fetchedArtifact.setHeatParameters(null);
1681 fetchedArtifact.setHeatParamsUpdateDate(null);
1685 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1686 StorageOperationStatus error = StorageOperationStatus.OK;
1687 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1688 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1689 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1694 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1696 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1698 if (artifactById.isRight()) {
1699 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1700 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1701 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1702 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1703 return Either.right(responseFormat);
1705 ArtifactDefinition artifactDefinition = artifactById.left().value();
1706 if (artifactDefinition == null) {
1707 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1709 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1710 return Either.right(responseFormat);
1713 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1714 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1715 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1716 return Either.left(insideEither);
1719 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1720 ComponentTypeEnum componentType) {
1722 String artifactLabel = artifactInfo.getArtifactLabel();
1723 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1725 BeEcompErrorManager.getInstance()
1726 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1727 log.debug("missing artifact logical name for component {}", componentId);
1728 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1730 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1732 if (operationName != null) {
1733 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1734 log.debug("artifact label cannot be set {}", artifactLabel);
1735 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1738 artifactLabel = operationName;
1741 String displayName = artifactInfo.getArtifactDisplayName();
1742 if (displayName == null || displayName.isEmpty()) {
1743 displayName = artifactLabel;
1745 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1746 artifactInfo.setArtifactDisplayName(displayName);
1748 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1749 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1750 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1752 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1754 if (artifactLabel.isEmpty()) {
1755 log.debug("missing normalized artifact logical name for component {}", componentId);
1756 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1759 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1760 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1761 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1762 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1764 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1765 log.debug("Non unique Artifact label : {}", artifactLabel);
1766 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1769 artifactInfo.setArtifactLabel(artifactLabel);
1771 return Either.left(ActionStatus.OK);
1774 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1775 boolean isUnique = true;
1776 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1777 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1778 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1781 artifacts = artifactToscaOperation.getArtifacts(componentId);
1784 if (artifacts.isLeft()) {
1785 for (String label : artifacts.left().value().keySet()) {
1786 if (label.equals(artifactLabel)) {
1792 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1793 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1794 .getAllInterfacesOfResource(componentId, true, true);
1795 if (allInterfacesOfResource.isLeft()) {
1796 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1797 for (Operation operation : interace.getOperationsMap().values()) {
1798 if (operation.getImplementation() != null && operation.getImplementation()
1800 .equals(artifactLabel)) {
1811 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1812 ComponentTypeEnum componentType) {
1813 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1814 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1815 String artifactName = artifactInfo.getArtifactName();
1816 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1817 if (artifacts.left().value().values().stream()
1818 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1819 //check whether it is the same artifact we hold (by label)
1820 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1824 if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1825 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1830 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1831 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1832 .getAllInterfacesOfResource(componentId, true, true);
1834 if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1835 return !allInterfacesOfResource.left().value()
1837 .stream().map(InterfaceDefinition :: getOperationsMap)
1838 .flatMap(map -> map.values().stream())
1839 .map(OperationDataDefinition::getImplementation)
1840 .filter(Objects::nonNull)
1841 .anyMatch(add -> artifactName.equals(add.getArtifactName())
1842 && !artifactLabel.equals(add.getArtifactLabel()));
1847 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1848 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1849 .getAllInterfacesOfResource(componentId, true, true);
1851 if (allInterfacesOfResource.isLeft()){
1852 return !allInterfacesOfResource.left().value()
1854 .stream().map(InterfaceDefinition :: getOperationsMap)
1855 .flatMap(map -> map.values().stream())
1856 .map(OperationDataDefinition::getImplementation)
1857 .filter(Objects::nonNull)
1858 .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1863 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1864 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1865 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1866 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1867 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1870 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1872 if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1873 log.debug("failed to retrieve artifacts for {} ", componentId);
1874 return Either.right(artifactsResponse.right().value());
1876 return Either.left(artifactsResponse.left().value().entrySet()
1878 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1879 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1882 private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1883 return artifacts.entrySet()
1885 .map(x -> x.getValue().getArtifactName())
1886 .collect(Collectors.toList());
1889 // ***************************************************************
1891 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1892 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1893 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1894 Either<ArtifactDefinition, Operation> insideEither = null;
1895 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1896 String instanceId = null;
1897 String instanceName = null;
1898 if (foundInstance != null) {
1899 instanceId = foundInstance.getUniqueId();
1900 instanceName = foundInstance.getName();
1902 boolean isLeft = false;
1903 String artifactUniqueId = null;
1904 StorageOperationStatus error = null;
1905 // information/deployment/api aritfacts
1906 log.trace("Try to create entry on graph");
1907 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1908 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1909 .getUniqueId(), nodeType, true, instanceId);
1911 isLeft = result.isLeft();
1913 artifactUniqueId = result.left().value().getUniqueId();
1914 result.left().value();
1916 insideEither = Either.left(result.left().value());
1917 resultOp = Either.left(insideEither);
1919 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1920 if (error != StorageOperationStatus.OK) {
1926 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1927 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1931 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1932 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1933 .getArtifactDisplayName());
1934 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1935 resultOp = Either.right(responseFormat);
1941 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1942 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1944 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1945 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1946 Either<ArtifactDefinition, Operation> insideEither = null;
1947 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1948 String instanceId = null;
1949 String instanceName = null;
1950 if (foundInstance != null) {
1951 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1952 log.debug("Failed to create artifact, already exists");
1953 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1954 .getArtifactLabel());
1955 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1957 resultOp = Either.right(responseFormat);
1961 instanceId = foundInstance.getUniqueId();
1962 instanceName = foundInstance.getName();
1964 if (artifactData == null) {
1965 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1966 log.debug("Failed to create artifact object for ES.");
1967 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1968 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1969 resultOp = Either.right(responseFormat);
1973 // set on graph object id of artifact in ES!
1974 artifactInfo.setEsId(artifactData.getId());
1976 boolean isLeft = false;
1977 String artifactUniqueId = null;
1978 StorageOperationStatus error = null;
1979 if (interfaceType != null && operationName != null) {
1980 // lifecycle artifact
1981 Operation operation = convertToOperation(artifactInfo, operationName);
1983 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1985 isLeft = result.isLeft();
1987 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1988 result.left().value().getImplementation();
1990 insideEither = Either.right(result.left().value());
1991 resultOp = Either.left(insideEither);
1994 error = result.right().value();
1998 // information/deployment/api aritfacts
1999 log.trace("Try to create entry on graph");
2000 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2001 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2002 .getUniqueId(), nodeType, true, instanceId);
2004 isLeft = result.isLeft();
2006 artifactUniqueId = result.left().value().getUniqueId();
2007 artifactData.setId(result.left().value().getEsId());
2008 insideEither = Either.left(result.left().value());
2009 resultOp = Either.left(insideEither);
2011 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2012 if (error != StorageOperationStatus.OK) {
2018 error = result.right().value();
2022 boolean res = saveArtifacts(artifactData, parentId);
2025 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2027 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2028 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2032 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2033 log.debug(FAILED_SAVE_ARTIFACT);
2034 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2035 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2037 resultOp = Either.right(responseFormat);
2042 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2043 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2044 .getArtifactDisplayName());
2045 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2046 resultOp = Either.right(responseFormat);
2052 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2053 ComponentInstance foundInstance = null;
2054 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2055 foundInstance = containerComponent.getComponentInstances()
2057 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2061 return foundInstance;
2064 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2066 Either<Boolean, ResponseFormat> result = Either.left(true);
2067 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
2069 validateArtifactTypeExists(responseWrapper, artifactInfo);
2071 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2073 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2075 if (responseWrapper.isEmpty()) {
2076 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2079 // Common code for all types
2080 // not allowed to change artifactType
2081 if (responseWrapper.isEmpty() && !isCreate) {
2082 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2083 if (validateServiceApiType.isRight()) {
2084 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2087 if (responseWrapper.isEmpty()) {
2088 if (parentType.equals(NodeTypeEnum.Resource)) {
2089 Resource resource = (Resource) parentComponent;
2090 ResourceTypeEnum resourceType = resource.getResourceType();
2091 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2092 if (config == null) {
2093 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2094 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2095 .getArtifactType()));
2098 List<String> myList = config.getValidForResourceTypes();
2099 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2100 if (either.isRight()) {
2101 responseWrapper.setInnerElement(either.right().value());
2106 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2109 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2110 String artifactName = artifactInfo.getArtifactName();
2111 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2112 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2116 if (responseWrapper.isEmpty()) {
2117 switch (artifactType) {
2121 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2124 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2125 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2127 case DCAE_INVENTORY_TOSCA:
2128 case DCAE_INVENTORY_JSON:
2129 case DCAE_INVENTORY_POLICY:
2130 // Validation is done in handle payload.
2131 case DCAE_INVENTORY_DOC:
2132 case DCAE_INVENTORY_BLUEPRINT:
2133 case DCAE_INVENTORY_EVENT:
2134 // No specific validation
2136 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2142 if (!responseWrapper.isEmpty()) {
2143 result = Either.right(responseWrapper.getInnerElement());
2148 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2149 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2150 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2151 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2152 .getArtifactType());
2153 responseWrapper.setInnerElement(responseFormat);
2154 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2158 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2159 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2160 if (parentType.equals(NodeTypeEnum.Resource)) {
2161 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2163 .getResourceDeploymentArtifacts();
2165 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2166 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2168 .getResourceInstanceDeploymentArtifacts();
2171 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2173 .getServiceDeploymentArtifacts();
2175 return resourceDeploymentArtifacts;
2178 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2179 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2180 if (artifactType == null) {
2181 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2182 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2183 .getArtifactType());
2184 responseWrapper.setInnerElement(responseFormat);
2185 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2189 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2190 ArtifactTypeConfig retConfig = null;
2191 String fileType = artifactType.getType();
2192 if (parentType.equals(NodeTypeEnum.Resource)) {
2193 retConfig = ConfigurationManager.getConfigurationManager()
2195 .getResourceDeploymentArtifacts()
2198 else if (parentType.equals(NodeTypeEnum.Service)) {
2199 retConfig = ConfigurationManager.getConfigurationManager()
2201 .getServiceDeploymentArtifacts()
2204 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2205 retConfig = ConfigurationManager.getConfigurationManager()
2207 .getResourceInstanceDeploymentArtifacts()
2213 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2214 // extract heat parameters
2215 if (artifactInfo.getPayloadData() != null) {
2216 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2217 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2218 .getArtifactType());
2219 if (heatParameters.isRight() && (!heatParameters.right()
2221 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2222 log.info("failed to parse heat parameters ");
2223 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2224 .getArtifactType());
2225 return Either.right(responseFormat);
2227 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2228 artifactInfo.setListHeatParameters(heatParameters.left().value());
2231 return Either.left(true);
2236 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2237 String fileType = artifactType.getType();
2238 List<String> acceptedTypes = null;
2239 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2240 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2241 log.debug("parent type of artifact can be either resource or service");
2242 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2246 if (deploymentAcceptedTypes == null) {
2247 log.debug("parent type of artifact can be either resource or service");
2248 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2249 .getArtifactType()));
2253 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2256 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2259 String artifactName = artifactInfo.getArtifactName();
2260 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2261 // Pavel - File extension validation is case-insensitive - Ella,
2263 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2264 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2265 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2270 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2272 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
2273 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
2274 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2276 if (errorWrapper.isEmpty()) {
2277 validateValidYaml(errorWrapper, artifactInfo);
2280 if (errorWrapper.isEmpty()) {
2281 // Validate Heat Exist
2282 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2283 .getComponentType());
2286 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2287 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2290 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2291 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2295 Either<Boolean, ResponseFormat> eitherResponse;
2296 if (errorWrapper.isEmpty()) {
2297 eitherResponse = Either.left(true);
2300 eitherResponse = Either.right(errorWrapper.getInnerElement());
2302 return eitherResponse;
2305 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2306 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2307 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2308 if (fillArtifactPayload.isRight()) {
2309 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2310 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2314 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2318 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2319 Either<Boolean, ResponseFormat> result = Either.left(true);
2320 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2322 if (eitherArtifactData.isLeft()) {
2323 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2324 data = Base64.encodeBase64(data);
2325 payloadWrapper.setInnerElement(data);
2328 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2331 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2332 result = Either.right(responseFormat);
2338 @SuppressWarnings("unchecked")
2339 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2340 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2341 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2342 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2343 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2345 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2346 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2347 if (eitherHeatEnvProperties.isRight()) {
2348 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2349 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2350 errorWrapper.setInnerElement(responseFormat);
2351 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2353 else if (eitherHeatProperties.isRight()) {
2354 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2355 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2356 .getArtifactName(), heatArtifact.getArtifactName());
2357 errorWrapper.setInnerElement(responseFormat);
2358 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2359 .getArtifactName());
2362 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2363 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2364 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2365 if (!heatEnvPropertiesKeys.isEmpty()) {
2366 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2367 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2368 .getArtifactName(), heatArtifact.getArtifactName());
2369 errorWrapper.setInnerElement(responseFormat);
2374 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2375 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2376 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2378 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2379 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2380 .getArtifactType());
2381 errorWrapper.setInnerElement(responseFormat);
2382 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2386 private boolean isValidXml(byte[] xmlToParse) {
2387 boolean isXmlValid = true;
2389 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2390 setFeatures(reader);
2391 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2393 catch (ParserConfigurationException | IOException | SAXException e) {
2394 log.debug("Xml is invalid : {}", e.getMessage(), e);
2400 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2402 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2403 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2405 catch (SAXNotRecognizedException e) {
2406 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2410 private boolean isValidJson(byte[] jsonToParse) {
2411 String parsed = new String(jsonToParse);
2413 gson.fromJson(parsed, Object.class);
2415 catch (Exception e) {
2416 log.debug("Json is invalid : {}", e.getMessage(), e);
2422 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2423 boolean artifactNameFound = false;
2424 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2427 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2428 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2430 if (artifactNameFound) {
2431 String parentName = parentComponent.getName();
2432 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2433 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2434 .name(), parentName, artifactName);
2436 errorWrapper.setInnerElement(responseFormat);
2437 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2442 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2443 ComponentTypeEnum componentType) {
2444 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2445 if (res.isRight()) {
2446 ResponseFormat responseFormat;
2447 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2448 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2451 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2453 errorWrapper.setInnerElement(responseFormat);
2456 ArtifactDefinition heatArtifact = res.left().value();
2457 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2460 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2461 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2462 // timeout > 0 for HEAT artifacts
2463 Integer timeout = artifactInfo.getTimeout();
2464 if (timeout == null) {
2465 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2466 artifactInfo.setTimeout(defaultTimeout);
2467 // HEAT artifact but timeout is invalid
2469 else if (timeout < 1) {
2470 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2473 // US649856 - Allow several HEAT files on Resource
2474 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2475 return Either.left(true);
2478 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2479 String listToString = (typeList != null) ? typeList.toString() : "";
2480 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2481 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2482 .getArtifactName(), listToString, resourceType.getValue());
2483 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2484 String resourceTypeName = resourceType.name();
2485 if (typeList != null && typeList.contains(resourceTypeName)) {
2486 either = Either.left(true);
2491 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2492 if (artifactInfo.getHeatParameters() != null) {
2493 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2494 String parameterType = heatParam.getType();
2495 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2496 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2497 if (heatParameterType == null) {
2498 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2500 return Either.right(responseFormat);
2503 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2504 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2505 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2506 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2507 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2508 .getType(), heatParam.getName());
2509 return Either.right(responseFormat);
2513 return Either.left(artifactInfo);
2516 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2517 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2518 if (parentComponent.getDeploymentArtifacts() != null) {
2519 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2520 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2521 if (getRI.isRight()) {
2522 return deploymentArtifacts;
2524 ComponentInstance ri = getRI.left().value();
2525 if (ri.getDeploymentArtifacts() != null) {
2526 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2529 else if (parentComponent.getDeploymentArtifacts() != null) {
2530 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2533 return deploymentArtifacts;
2536 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2537 // on create if null add informational to current
2538 if (artifactInfo.getArtifactGroupType() == null) {
2539 artifactInfo.setArtifactGroupType(type);
2541 if (artifactInfo.getUniqueId() != null) {
2542 log.error("artifact uniqid cannot be set ignoring");
2544 artifactInfo.setUniqueId(null);
2546 if (artifactInfo.getArtifactRef() != null) {
2547 log.error("artifact ref cannot be set ignoring");
2549 artifactInfo.setArtifactRef(null);
2551 if (artifactInfo.getArtifactRepository() != null) {
2552 log.error("artifact repository cannot be set ignoring");
2554 artifactInfo.setArtifactRepository(null);
2556 if (artifactInfo.getUserIdCreator() != null) {
2557 log.error("creator uuid cannot be set ignoring");
2559 artifactInfo.setArtifactCreator(user.getUserId());
2561 if (artifactInfo.getUserIdLastUpdater() != null) {
2562 log.error("userId of last updater cannot be set ignoring");
2564 artifactInfo.setUserIdLastUpdater(user.getUserId());
2566 if (artifactInfo.getCreatorFullName() != null) {
2567 log.error("creator Full name cannot be set ignoring");
2569 String fullName = user.getFirstName() + " " + user.getLastName();
2570 artifactInfo.setUpdaterFullName(fullName);
2572 if (artifactInfo.getUpdaterFullName() != null) {
2573 log.error("updater Full name cannot be set ignoring");
2575 artifactInfo.setUpdaterFullName(fullName);
2577 if (artifactInfo.getCreationDate() != null) {
2578 log.error("Creation Date cannot be set ignoring");
2580 long time = System.currentTimeMillis();
2581 artifactInfo.setCreationDate(time);
2583 if (artifactInfo.getLastUpdateDate() != null) {
2584 log.error("Last Update Date cannot be set ignoring");
2586 artifactInfo.setLastUpdateDate(time);
2588 if (artifactInfo.getEsId() != null) {
2589 log.error("es id cannot be set ignoring");
2591 artifactInfo.setEsId(null);
2596 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2597 String id = artifactId;
2598 if (artifactId == null || artifactId.isEmpty()) {
2599 String uniqueId = null;
2600 if (interfaceName != null && operationName != null) {
2601 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2602 .getArtifactLabel());
2605 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2607 artifactInfo.setUniqueId(uniqueId);
2608 artifactInfo.setEsId(uniqueId);
2612 artifactInfo.setUniqueId(artifactId);
2613 artifactInfo.setEsId(artifactId);
2618 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2619 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2620 BeEcompErrorManager.getInstance()
2621 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2622 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2623 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2626 boolean artifactTypeExist = false;
2627 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2628 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2630 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2631 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2635 allArtifactTypes = elementOperation.getAllArtifactTypes();
2637 if (allArtifactTypes.isRight()) {
2638 BeEcompErrorManager.getInstance()
2639 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2643 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2645 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2648 for (ArtifactType type : allArtifactTypes.left().value()) {
2649 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2650 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2651 artifactTypeExist = true;
2656 if (!artifactTypeExist) {
2657 BeEcompErrorManager.getInstance()
2658 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2659 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2660 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2661 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2662 .getArtifactType()));
2665 return Either.left(ActionStatus.OK);
2668 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2670 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2671 List<ArtifactType> artifactTypes = new ArrayList<>();
2673 if (parentType.equals(NodeTypeEnum.Service)) {
2674 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2676 .getServiceDeploymentArtifacts();
2678 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2679 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2681 .getResourceInstanceDeploymentArtifacts();
2684 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2686 .getResourceDeploymentArtifacts();
2688 if (deploymentArtifacts != null) {
2689 for (String artifactType : deploymentArtifacts.keySet()) {
2690 ArtifactType artifactT = new ArtifactType();
2691 artifactT.setName(artifactType);
2692 artifactTypes.add(artifactT);
2694 return Either.left(artifactTypes);
2697 return Either.right(ActionStatus.GENERAL_ERROR);
2702 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2703 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2704 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2706 return Either.left(true);
2710 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2711 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2712 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2715 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2716 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2717 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2719 artifactInfo.setArtifactName(normalizeFileName);
2721 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2722 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2725 return Either.left(true);
2728 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2729 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2730 log.info("artifact type is missing operation ignored");
2731 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2734 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2735 log.info("artifact type cannot be changed operation ignored");
2736 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2738 return Either.left(true);
2741 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2742 if (artifactInfo.getArtifactGroupType() == null) {
2743 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2746 else if (!currentArtifact.getArtifactGroupType()
2748 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2749 log.info("artifact group type cannot be changed. operation failed");
2750 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2752 return Either.left(artifactInfo);
2755 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2757 // on update if null add informational to current
2758 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2759 currentArtifact.setArtifactGroupType(type);
2762 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2763 log.error("artifact uniqid cannot be set ignoring");
2765 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2767 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2768 .equals(artifactInfo.getArtifactRef())) {
2769 log.error("artifact ref cannot be set ignoring");
2771 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2773 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2774 .equals(artifactInfo.getArtifactRepository())) {
2775 log.error("artifact repository cannot be set ignoring");
2777 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2779 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2780 .equals(artifactInfo.getUserIdCreator())) {
2781 log.error("creator uuid cannot be set ignoring");
2783 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2785 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2786 .equals(artifactInfo.getArtifactCreator())) {
2787 log.error("artifact creator cannot be set ignoring");
2789 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2791 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2792 .equals(artifactInfo.getUserIdLastUpdater())) {
2793 log.error("userId of last updater cannot be set ignoring");
2795 artifactInfo.setUserIdLastUpdater(user.getUserId());
2797 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2798 .equals(artifactInfo.getCreatorFullName())) {
2799 log.error("creator Full name cannot be set ignoring");
2801 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2803 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2804 .equals(artifactInfo.getUpdaterFullName())) {
2805 log.error("updater Full name cannot be set ignoring");
2807 String fullName = user.getFirstName() + " " + user.getLastName();
2808 artifactInfo.setUpdaterFullName(fullName);
2810 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2811 .equals(artifactInfo.getCreationDate())) {
2812 log.error("Creation Date cannot be set ignoring");
2814 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2816 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2817 .equals(artifactInfo.getLastUpdateDate())) {
2818 log.error("Last Update Date cannot be set ignoring");
2820 long time = System.currentTimeMillis();
2821 artifactInfo.setLastUpdateDate(time);
2823 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2824 log.error("es id cannot be set ignoring");
2826 artifactInfo.setEsId(currentArtifact.getUniqueId());
2828 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2829 .equals(artifactInfo.getArtifactDisplayName())) {
2830 log.error(" Artifact Display Name cannot be set ignoring");
2832 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2834 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2835 .equals(artifactInfo.getServiceApi())) {
2836 log.debug("serviceApi cannot be set. ignoring.");
2838 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2840 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2841 .equals(artifactInfo.getArtifactGroupType())) {
2842 log.debug("artifact group cannot be set. ignoring.");
2844 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2846 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2848 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2849 .isEmpty() && !currentArtifact.getArtifactUUID()
2850 .equals(artifactInfo.getArtifactUUID())) {
2851 log.debug("artifact UUID cannot be set. ignoring.");
2853 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2855 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2856 .getHeatParameters()
2857 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2858 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2862 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2864 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2865 for (HeatParameterDefinition parameter : heatParameters) {
2866 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2868 if (currentParam != null) {
2870 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2871 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2872 parameter.setName(currentParam.getName());
2874 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2875 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2876 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2877 parameter.setDefaultValue(currentParam.getDefaultValue());
2879 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2880 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2881 parameter.setType(currentParam.getType());
2883 if (parameter.getDescription() != null && !parameter.getDescription()
2884 .equalsIgnoreCase(currentParam.getDescription())) {
2885 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2886 parameter.setDescription(currentParam.getDescription());
2889 // check and set current value
2890 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2891 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2892 parameter.setCurrentValue(currentParam.getDefaultValue());
2898 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2900 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2901 for (HeatParameterDefinition param : currentParameters) {
2902 currentParamsMap.put(param.getUniqueId(), param);
2904 return currentParamsMap;
2907 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2908 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2909 log.debug("Artifact url cannot be empty.");
2910 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2912 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2914 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2915 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2917 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2918 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2921 return Either.left(true);
2924 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2925 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2926 log.debug("Artifact description cannot be empty.");
2927 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2929 String description = artifactInfo.getDescription();
2930 description = ValidationUtils.removeNoneUtf8Chars(description);
2931 description = ValidationUtils.normaliseWhitespace(description);
2932 description = ValidationUtils.stripOctets(description);
2933 description = ValidationUtils.removeHtmlTagsOnly(description);
2934 if (!ValidationUtils.validateIsEnglish(description)) {
2935 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2937 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2938 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2939 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2941 artifactInfo.setDescription(description);
2942 return Either.left(true);
2945 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2946 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2947 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2948 String prevArtifactId = null;
2949 String currArtifactId = artifactId;
2951 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2952 Either<ArtifactDefinition, Operation> insideEither = null;
2954 log.trace("Try to update entry on graph");
2955 String artifactUniqueId = null;
2956 ArtifactDefinition artifactDefinition = artifactInfo;
2957 StorageOperationStatus error;
2960 if (interfaceType == null || operationUuid == null) {
2961 log.debug("Entity on graph is updated. Update artifact in ES");
2963 // Changing previous and current artifactId for auditing
2964 prevArtifactId = currArtifactId;
2965 currArtifactId = artifactDefinition.getUniqueId();
2968 if (decodedPayload == null) {
2969 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2970 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2972 if (artifactFromCassandra.isRight()) {
2973 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2974 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2976 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2977 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2978 resultOp = Either.right(responseFormat);
2981 // clone data to new artifact
2982 artifactData.setData(artifactFromCassandra.left().value().getData());
2983 artifactData.setId(artifactFromCassandra.left().value().getId());
2986 if (artifactDefinition.getEsId() == null) {
2987 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2988 artifactData.setId(artifactDefinition.getUniqueId());
2992 NodeTypeEnum convertParentType = convertParentType(componentType);
2993 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
2994 .getUniqueId(), artifactId, convertParentType, parentId);
2995 isLeft = result.isLeft();
2997 artifactUniqueId = result.left().value().getUniqueId();
2998 artifactDefinition = result.left().value();
2999 String artifactType = artifactInfo.getArtifactType();
3000 if (NodeTypeEnum.Resource == convertParentType
3001 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3002 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3003 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3004 && !artifactUniqueId.equals(artifactId)) {
3005 // need to update the generated id in heat env
3006 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3007 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3009 .filter(a -> a.getValue()
3010 .getGeneratedFromId() != null && a
3012 .getGeneratedFromId()
3013 .equals(artifactId))
3015 if (findFirst.isPresent()) {
3016 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3017 artifactEnvInfo.setArtifactChecksum(null);
3018 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3021 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3023 insideEither = Either.left(result.left().value());
3024 resultOp = Either.left(insideEither);
3025 if (error != StorageOperationStatus.OK) {
3030 error = result.right().value();
3034 // create new entry in ES
3036 if (artifactData.getData() != null) {
3037 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3038 artifactData.setId(artifactDefinition.getEsId());
3040 res = saveArtifacts(artifactData, parentId);
3046 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3047 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3048 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3050 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3051 log.debug(FAILED_SAVE_ARTIFACT);
3052 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3053 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3054 resultOp = Either.right(responseFormat);
3057 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3058 decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
3059 currArtifactId, artifactDefinition);
3065 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3066 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3067 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
3068 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3069 ArtifactDefinition artifactDefinition) {
3070 StorageOperationStatus error;
3071 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3072 if (decodedPayload == null) {
3073 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3074 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3076 if (artifactFromCassandra.isRight()) {
3077 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3078 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3080 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3081 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3082 resultOp = Either.right(responseFormat);
3085 // clone data to new artifact
3086 artifactData.setData(artifactFromCassandra.left().value().getData());
3087 artifactData.setId(artifactFromCassandra.left().value().getId());
3089 // todo if not exist(first time)
3093 if (artifactDefinition.getEsId() == null) {
3094 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3095 artifactData.setId(artifactDefinition.getUniqueId());
3098 NodeTypeEnum convertParentType = convertParentType(componentType);
3099 // fetch the resource from storage
3100 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither =
3101 toscaOperationFacade.getToscaElement(parentId);
3102 if (componentStorageOperationStatusEither.isRight()) {
3103 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
3104 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
3105 return Either.right(componentsUtils
3106 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
3108 Component storedComponent = componentStorageOperationStatusEither.left().value();
3110 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
3111 .getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
3112 if(!optionalInterface.isPresent()) {
3113 log.debug("Failed to get resource interface for resource Id {}", parentId);
3114 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
3117 //fetch the operation from storage
3118 InterfaceDefinition gotInterface = optionalInterface.get();
3119 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
3120 Optional<Operation> optionalOperation = operationsMap.values()
3122 .filter(o -> o.getUniqueId().equals(operationUuid))
3124 if (!optionalOperation.isPresent()) {
3125 log.debug("Failed to get resource interface operation for resource Id {} " +
3126 " and operationId {}", parentId, operationUuid);
3127 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3128 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3129 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3130 currArtifactId, responseFormat, componentType, null);
3131 return Either.right(responseFormat);
3134 Operation operation = optionalOperation.get();
3135 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
3136 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
3137 implementationArtifact.setDescription(artifactInfo.getDescription());
3138 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
3139 implementationArtifact.setArtifactLabel(artifactInfo.getUniqueId());
3140 implementationArtifact.setEsId(artifactInfo.getEsId());
3141 operation.setImplementation(implementationArtifact);
3142 gotInterface.setOperationsMap(operationsMap);
3143 Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
3144 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
3145 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
3146 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
3147 ActionStatus actionStatus =
3148 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
3149 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3152 String uniqueId = implementationArtifact.getUniqueId();
3153 artifactData.setId(uniqueId);
3154 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3155 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3156 log.debug("Failed to persist operation {} artifact, error is {}",operation.getName(),cassandraOperationStatus);
3157 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3158 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3159 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3161 return Either.left(Either.left(implementationArtifact));
3164 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3165 log.trace("Starting payload handling");
3166 byte[] payload = artifactInfo.getPayloadData();
3167 byte[] decodedPayload = null;
3169 if (payload != null && payload.length != 0) {
3170 // the generated artifacts were already decoded by the handler
3171 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3172 if (decodedPayload.length == 0) {
3173 log.debug("Failed to decode the payload.");
3174 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3175 return Either.right(responseFormat);
3178 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3179 artifactInfo.setArtifactChecksum(checkSum);
3180 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3182 // Specific payload validations of different types
3183 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
3184 if (isDeploymentArtifact(artifactInfo)) {
3185 log.trace("Starting deployment artifacts payload validation");
3186 String artifactType = artifactInfo.getArtifactType();
3187 if (ArtifactTypeEnum.HEAT.getType()
3188 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
3189 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
3191 .equalsIgnoreCase(artifactType)
3192 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3193 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
3194 if (isValidPayload.isLeft()) {
3195 isValidPayload = extractHeatParameters(artifactInfo);
3198 else if (ArtifactTypeEnum.YANG_XML.getType()
3199 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
3200 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
3202 .equalsIgnoreCase(artifactType)
3203 || ArtifactTypeEnum.VENDOR_LICENSE.getType()
3204 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
3206 .equalsIgnoreCase(artifactType)
3207 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
3208 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
3210 .equalsIgnoreCase(artifactType)) {
3211 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3213 else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
3214 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
3216 .equalsIgnoreCase(artifactType)
3217 || ArtifactTypeEnum.VES_EVENTS.getType()
3218 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
3220 .equalsIgnoreCase(artifactType)) {
3221 String artifactFileName = artifactInfo.getArtifactName();
3222 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
3223 switch (fileExtension) {
3225 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3228 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
3232 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
3239 if (isValidPayload.isRight()) {
3240 ResponseFormat responseFormat = isValidPayload.right().value();
3241 return Either.right(responseFormat);
3244 } // null/empty payload is normal if called from metadata update ONLY.
3245 // The validation of whether this is metadata/payload update case is
3246 // currently done separately
3248 if (!isArtifactMetadataUpdate) {
3249 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3250 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3251 return Either.right(responseFormat);
3254 log.trace("Ended payload handling");
3255 return Either.left(decodedPayload);
3258 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
3259 // Basic YAML validation
3260 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3261 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3262 log.debug("Invalid YAML format");
3263 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3264 return Either.right(responseFormat);
3266 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3267 // HEAT specific YAML validation
3268 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
3269 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
3270 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
3271 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
3272 return Either.right(responseFormat);
3276 return Either.left(true);
3279 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
3280 Either<Boolean, ResponseFormat> res = Either.left(true);
3281 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3282 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3283 log.debug("Invalid YAML format");
3284 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3285 res = Either.right(responseFormat);
3291 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
3292 boolean isXmlValid = isValidXml(payload);
3294 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3295 .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
3296 log.debug("Invalid XML content");
3297 return Either.right(responseFormat);
3299 return Either.left(true);
3302 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3303 boolean isJsonValid = isValidJson(payload);
3305 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3306 .getResponseFormat(ActionStatus.INVALID_JSON, type);
3307 log.debug("Invalid JSON content");
3308 return Either.right(responseFormat);
3310 return Either.left(true);
3313 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3314 boolean inTransaction) {
3315 User user = new User();
3316 user.setUserId(userUserId);
3317 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3318 if (parent.isRight()) {
3319 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3322 return Either.right(responseFormat);
3324 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3327 false, inTransaction);
3328 if (handleDelete.isRight()) {
3329 return Either.right(handleDelete.right().value());
3331 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3332 return Either.left(result.right().value());
3336 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3337 Operation op = new Operation();
3338 long time = System.currentTimeMillis();
3339 op.setCreationDate(time);
3341 String artifactName = artifactInfo.getArtifactName();
3342 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3344 op.setImplementation(artifactInfo);
3345 op.setLastUpdateDate(time);
3349 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3350 String newArtifactName = operationName + "_" + artifactName;
3351 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3352 return newArtifactName;
3356 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3358 // General validation
3359 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3360 log.debug(NULL_PARAMETER);
3361 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3364 // Normalizing artifact name
3365 artifactName = ValidationUtils.normalizeFileName(artifactName);
3367 // Resource validation
3368 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3369 if (validateResourceNameAndVersion.isRight()) {
3370 return Either.right(validateResourceNameAndVersion.right().value());
3373 Resource resource = validateResourceNameAndVersion.left().value();
3374 String resourceId = resource.getUniqueId();
3376 // Service validation
3377 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3378 if (validateServiceNameAndVersion.isRight()) {
3379 return Either.right(validateServiceNameAndVersion.right().value());
3382 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3383 if (artifacts == null || artifacts.isEmpty()) {
3384 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3385 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3388 ArtifactDefinition deploymentArtifact = null;
3390 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3391 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3392 .equals(artifactName)) {
3393 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3394 deploymentArtifact = artifactDefinition;
3399 if (deploymentArtifact == null) {
3400 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3401 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3404 // Downloading the artifact
3405 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3406 if (downloadArtifactEither.isRight()) {
3407 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3408 return Either.right(downloadArtifactEither.right().value());
3410 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3411 return Either.left(downloadArtifactEither.left().value().getRight());
3415 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3417 // General validation
3418 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3419 log.debug(NULL_PARAMETER);
3420 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3423 // Normalizing artifact name
3424 artifactName = ValidationUtils.normalizeFileName(artifactName);
3426 // Service validation
3427 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3428 if (validateServiceNameAndVersion.isRight()) {
3429 return Either.right(validateServiceNameAndVersion.right().value());
3432 Service service = validateServiceNameAndVersion.left().value();
3434 // ResourceInstance validation
3435 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3436 if (validateResourceInstance.isRight()) {
3437 return Either.right(validateResourceInstance.right().value());
3440 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3442 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3444 final String finalArtifactName = artifactName;
3445 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3447 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3449 .anyMatch(filterArtifactByName);
3450 ArtifactDefinition deployableArtifact;
3452 if (!hasDeploymentArtifacts) {
3453 log.debug("Deployment artifact with name {} not found", artifactName);
3454 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3457 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3458 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3459 // Downloading the artifact
3460 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3462 if (downloadArtifactEither.isRight()) {
3463 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3464 return Either.right(downloadArtifactEither.right().value());
3466 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3467 return Either.left(downloadArtifactEither.left().value().getRight());
3470 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3472 List<ComponentInstance> riList = service.getComponentInstances();
3473 for (ComponentInstance ri : riList) {
3474 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3475 return Either.left(ri);
3479 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3482 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3484 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3485 if (serviceListBySystemName.isRight()) {
3486 log.debug("Couldn't fetch any service with name {}", serviceName);
3487 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3489 .value(), ComponentTypeEnum.SERVICE), serviceName));
3491 List<Service> serviceList = serviceListBySystemName.left().value();
3492 if (serviceList == null || serviceList.isEmpty()) {
3493 log.debug("Couldn't fetch any service with name {}", serviceName);
3494 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3497 Service foundService = null;
3498 for (Service service : serviceList) {
3499 if (service.getVersion().equals(serviceVersion)) {
3500 log.trace("Found service with version {}", serviceVersion);
3501 foundService = service;
3506 if (foundService == null) {
3507 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3508 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3509 .getValue(), serviceVersion));
3511 return Either.left(foundService);
3514 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3516 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3517 if (resourceListBySystemName.isRight()) {
3518 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3519 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3521 .value()), resourceName));
3523 return Either.left(resourceListBySystemName.left().value());
3526 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3528 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3529 if (serviceName == null || serviceVersion == null || artifactName == null) {
3530 log.debug(NULL_PARAMETER);
3531 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3534 // Normalizing artifact name
3535 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3537 // Service validation
3538 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3539 if (validateServiceNameAndVersion.isRight()) {
3540 return Either.right(validateServiceNameAndVersion.right().value());
3543 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3545 // Looking for deployment or tosca artifacts
3546 Service service = validateServiceNameAndVersion.left().value();
3548 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3549 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3550 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3553 Optional<ArtifactDefinition> foundArtifactOptl = null;
3555 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3556 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3557 // filters artifact by name
3558 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3560 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3561 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3562 // filters TOSCA artifact by name
3563 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3565 if (!foundArtifactOptl.isPresent()) {
3566 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3567 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3569 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3570 // Downloading the artifact
3571 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3573 if (downloadArtifactEither.isRight()) {
3574 log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3575 return Either.right(downloadArtifactEither.right().value());
3577 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3578 return Either.left(downloadArtifactEither.left().value().getRight());
3581 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3582 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3583 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3584 if (artifactById.isRight()) {
3585 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3586 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3587 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3589 ArtifactDefinition artifactDefinition = artifactById.left().value();
3590 if (artifactDefinition == null) {
3591 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3592 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3595 return downloadArtifact(artifactDefinition);
3598 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3599 boolean found = false;
3600 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3601 if (artifactsS != null) {
3602 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3603 if (entry.getValue().getUniqueId().equals(artifactId)) {
3609 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3610 if (!found && deploymentArtifactsS != null) {
3611 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3612 if (entry.getValue().getUniqueId().equals(artifactId)) {
3618 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3619 if (!found && toscaArtifactsS != null) {
3620 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3621 if (entry.getValue().getUniqueId().equals(artifactId)) {
3628 Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3629 if (!found && interfaces != null) {
3630 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3631 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3632 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3633 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3634 .getImplementation()
3636 .equals(artifactId)) {
3644 switch (component.getComponentType()) {
3648 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3649 if (!found && apiArtifacts != null) {
3650 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3651 if (entry.getValue().getUniqueId().equals(artifactId)) {
3665 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3667 boolean found = false;
3668 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3669 ComponentInstance resourceInstance = null;
3670 for (ComponentInstance ri : resourceInstances) {
3671 if (ri.getUniqueId().equals(resourceInstanceId)) {
3672 resourceInstance = ri;
3676 if (resourceInstance != null) {
3677 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3678 if (artifacts != null) {
3679 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3680 if (entry.getValue().getUniqueId().equals(artifactId)) {
3687 artifacts = resourceInstance.getArtifacts();
3688 if (artifacts != null) {
3689 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3690 if (entry.getValue().getUniqueId().equals(artifactId)) {
3701 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3702 String containerComponentType) {
3704 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3705 componentForAudit.getNodeType();
3707 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3708 .getToscaFullElement(componentId);
3710 if (componentResult.isRight()) {
3711 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3712 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3713 log.debug("Service not found, serviceId {}", componentId);
3714 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3715 return Either.right(responseFormat);
3717 return Either.left(componentResult.left().value());
3720 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3721 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3722 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3723 if (canWork.isRight()) {
3724 String uniqueId = component.getUniqueId();
3725 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3726 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3728 .getComponentType(), null);
3729 return Either.right(canWork.right().value());
3732 return Either.left(true);
3735 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3737 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3738 String role = user.getRole();
3739 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3740 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3741 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3742 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3743 return Either.right(responseFormat);
3746 return Either.left(true);
3749 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3752 user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3753 } catch(ComponentException e){
3755 user.setUserId(userId);
3756 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
3757 componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3758 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3761 return Either.left(user);
3764 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3765 AuditingActionEnum auditingAction = null;
3766 switch (operation.getArtifactOperationEnum()) {
3768 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3771 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3774 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3777 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3782 return auditingAction;
3785 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3786 String esArtifactId = artifactDefinition.getEsId();
3787 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3788 if (artifactfromES.isRight()) {
3789 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3790 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3791 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3792 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3793 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3794 .getArtifactDisplayName());
3796 return Either.right(responseFormat);
3799 ESArtifactData esArtifactData = artifactfromES.left().value();
3800 byte[] data = esArtifactData.getDataAsArray();
3802 log.debug("Artifact data from ES is null");
3803 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3805 String artifactName = artifactDefinition.getArtifactName();
3806 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3807 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3810 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3811 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3814 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3815 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3817 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3818 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3821 log.info("Failed to save artifact {}.", artifactData.getId());
3827 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3828 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3831 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3832 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3835 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3836 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3837 if (user.isRight()) {
3838 ResponseFormat responseFormat;
3839 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3840 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3841 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3844 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3845 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3847 return Either.right(responseFormat);
3850 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3852 .value(), groupType);
3853 return Either.left(artifactDefinition);
3856 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3857 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3859 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3860 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3861 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3863 artifactInfo.setArtifactDisplayName(artifactName);
3864 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3865 artifactInfo.setArtifactType(artifactType);
3866 artifactInfo.setDescription(artifactDescription);
3867 artifactInfo.setArtifactGroupType(groupType);
3868 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3870 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3872 return artifactInfo;
3875 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3876 String uniqueId = null;
3878 if (resourceId != null) {
3879 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3881 artifactInfo.setUniqueId(uniqueId);
3883 artifactInfo.setUserIdCreator(user.getUserId());
3884 String fullName = user.getFullName();
3885 artifactInfo.setUpdaterFullName(fullName);
3887 long time = System.currentTimeMillis();
3889 artifactInfo.setCreatorFullName(fullName);
3890 artifactInfo.setCreationDate(time);
3892 artifactInfo.setLastUpdateDate(time);
3893 artifactInfo.setUserIdLastUpdater(user.getUserId());
3895 artifactInfo.setMandatory(true);
3898 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3899 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3902 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3903 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3906 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3908 byte[] payload = payloadStr.getBytes();
3910 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3911 return Either.left(artifactData);
3915 * @param artifactDefinition
3918 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3919 String instanceId, boolean shouldLock, boolean inTransaction) {
3920 String payload = generateHeatEnvPayload(artifactDefinition);
3921 String prevUUID = artifactDefinition.getArtifactUUID();
3922 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3923 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3925 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3928 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3929 boolean shouldLock, boolean inTransaction, String instanceId) {
3930 String payload = generateHeatEnvPayload(artifactDefinition);
3931 String prevUUID = artifactDefinition.getArtifactUUID();
3932 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3933 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3935 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3938 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3939 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3940 List<ComponentInstance> componentInstances = component.getComponentInstances();
3941 if (componentInstances != null) {
3942 Optional<ComponentInstance> findFirst = componentInstances.stream()
3943 .filter(ci -> ci.getUniqueId()
3944 .equals(instanceId))
3946 if (findFirst.isPresent()) {
3947 ComponentInstance relevantInst = findFirst.get();
3948 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3949 .getGroupInstances());
3951 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3952 updatedGroupInstances.forEach(gi -> {
3953 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3954 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3956 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3957 if (status.isRight()) {
3958 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3959 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3960 .convertFromStorageResponse(status.right()
3961 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3962 return Either.right(responseFormat);
3968 return Either.left(updatedArtDef);
3971 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3972 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3973 StringBuilder sb = new StringBuilder();
3974 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3975 sb.append("parameters:\n");
3976 if (heatParameters != null) {
3977 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3979 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3981 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3983 String heatValue = heatParameterDefinition.getCurrentValue();
3984 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3985 heatValue = heatParameterDefinition.getDefaultValue();
3986 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3987 empltyHeatValues.add(heatParameterDefinition);
3991 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3996 .append(heatParameterDefinition.getName())
3999 .append(Boolean.parseBoolean(heatValue))
4004 .append(heatParameterDefinition.getName())
4007 .append(new BigDecimal(heatValue).toPlainString())
4010 case COMMA_DELIMITED_LIST:
4013 .append(heatParameterDefinition.getName())
4020 String value = heatValue;
4021 boolean starts = value.startsWith("\"");
4022 boolean ends = value.endsWith("\"");
4023 if (!(starts && ends)) {
4024 starts = value.startsWith("'");
4025 ends = value.endsWith("'");
4026 if (!(starts && ends)) {
4027 value = "\"" + value + "\"";
4031 .append(heatParameterDefinition.getName())
4041 if (!empltyHeatValues.isEmpty()) {
4042 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
4043 empltyHeatValues.forEach(hv -> {
4044 sb.append(" ").append(hv.getName()).append(":");
4045 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
4046 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
4047 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
4048 sb.append(" \"\"").append("\n");
4051 sb.append(" ").append("\n");
4056 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
4059 return sb.toString().replaceAll("\\\\n", "\n");
4063 * @param artifactDefinition
4067 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4068 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4069 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
4070 .getHeatParamsUpdateDate(),
4071 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4075 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4076 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4077 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
4078 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4082 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
4083 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
4085 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
4087 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
4088 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
4090 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
4091 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
4092 ESArtifactData artifactData = null;
4094 if (artifactDataRes.isLeft()) {
4095 artifactData = artifactDataRes.left().value();
4098 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4099 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4100 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4101 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4103 return Either.right(artifactDataRes.right().value());
4105 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4107 String esArtifactId = artifactDefinition.getEsId();
4108 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4109 ESArtifactData esArtifactData;
4110 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4111 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4112 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4113 if (artifactfromES.isRight()) {
4114 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4115 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4116 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4117 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4118 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4120 esArtifactData = artifactfromES.left().value();
4121 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4124 oldCheckSum = artifactDefinition.getArtifactChecksum();
4127 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4130 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4131 if (lockComponent.isRight()) {
4132 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4133 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4134 return Either.right(lockComponent.right().value());
4138 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4140 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4141 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4142 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4143 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4144 .getArtifactType(), artifactDefinition.getEsId());
4145 if (updateArifactDefinitionStatus.isRight()) {
4146 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4148 .value()), artifactDefinition.getArtifactDisplayName());
4149 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4150 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4151 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4152 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4154 return Either.right(responseFormat);
4159 oldCheckSum = artifactDefinition.getArtifactChecksum();
4160 artifactDefinition.setArtifactChecksum(newCheckSum);
4161 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4162 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4163 .getArtifactType(), artifactDefinition.getEsId());
4164 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4165 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4167 log.trace("Update Payload ", artifactDefinition.getEsId());
4169 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4171 artifactDefinition = updateArifactDefinitionStatus.left().value();
4172 artifactData.setId(artifactDefinition.getUniqueId());
4173 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4175 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4176 if (!inTransaction) {
4179 log.debug("Artifact Saved In ES {}", artifactData.getId());
4180 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4181 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4182 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4183 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4187 if (!inTransaction) {
4188 titanDao.rollback();
4190 log.info("Failed to save artifact {}.", artifactData.getId());
4191 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4192 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4193 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4194 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4196 return Either.right(responseFormat);
4200 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4202 .value()), artifactDefinition.getArtifactDisplayName());
4203 log.debug("Failed To update artifact {}", artifactData.getId());
4204 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4205 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4206 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4208 return Either.right(responseFormat);
4214 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4220 return Either.left(artifactDefinition);
4224 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4225 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4226 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4227 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4231 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4232 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4234 Map<String, Object> json = new HashMap<>();
4235 if (artifactId != null && !artifactId.isEmpty()) {
4236 json.put(Constants.ARTIFACT_ID, artifactId);
4239 json.put(Constants.ARTIFACT_NAME, artifactName);
4240 json.put(Constants.ARTIFACT_TYPE, artifactType);
4241 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4243 if (artifactContent != null) {
4244 log.debug("payload is encoded. perform decode");
4245 String encodedPayload = Base64.encodeBase64String(artifactContent);
4246 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4248 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4249 json.put(Constants.ARTIFACT_LABEL, label);
4250 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4251 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4252 : updatedRequiredArtifacts.stream()
4253 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4255 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4256 .map(e -> e.getFileName())
4257 .collect(Collectors.toList()));
4258 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4263 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4265 String jsonStr = gson.toJson(json);
4266 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4267 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4268 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4269 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4270 if (uploadArtifactToService.isRight()) {
4271 return Either.right(uploadArtifactToService.right().value());
4274 return Either.left(uploadArtifactToService.left().value());
4277 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4278 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4279 convertParentType(componentType);
4280 String parentId = parent.getUniqueId();
4281 ArtifactDefinition currArtifact = artifactInfo;
4283 if (origMd5 != null) {
4284 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4285 if (validateMd5.isRight()) {
4286 ResponseFormat responseFormat = validateMd5.right().value();
4287 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4288 return Either.right(responseFormat);
4291 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4292 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4293 if (deploymentValidationResult.isRight()) {
4294 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4295 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4296 return Either.right(responseFormat);
4299 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4300 if (payloadEither.isRight()) {
4301 ResponseFormat responseFormat = payloadEither.right().value();
4302 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4303 return Either.right(responseFormat);
4307 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4308 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4309 return Either.right(responseFormat);
4315 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4316 if (lockComponent.isRight()) {
4317 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4318 .value(), componentType, null);
4319 return Either.right(lockComponent.right().value());
4322 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4324 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4330 if (resultOp == null || resultOp.isRight()) {
4331 log.debug(ROLLBACK);
4332 if (!inTransaction) {
4333 titanDao.rollback();
4338 if (!inTransaction) {
4343 componentType = parent.getComponentType();
4345 NodeTypeEnum nodeType = componentType.getNodeType();
4346 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4350 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4351 ComponentTypeEnum componentType, String origMd5) {
4353 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4354 Either<ArtifactDefinition, Operation> insideEither = null;
4355 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4356 if (getRI.isRight()) {
4357 return Either.right(getRI.right().value());
4359 ComponentInstance ri = getRI.left().value();
4360 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4361 if (getArtifactRes.isRight()) {
4362 return Either.right(getArtifactRes.right().value());
4364 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4366 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4367 .equals(ArtifactTypeEnum.HEAT_VOL
4368 .getType()) || currArtifact
4370 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4371 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4372 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4374 return Either.right(responseFormat);
4376 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4377 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4378 new ArrayList<HeatParameterDefinition>();
4381 if (origMd5 != null) {
4382 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4383 .getName(), currentHeatEnvParams,
4384 updatedHeatEnvParams, currArtifact.getArtifactName());
4385 if (uploadParamsValidationResult.isRight()) {
4386 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4387 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4389 return Either.right(responseFormat);
4391 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4394 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4396 if (validateAndConvertHeatParamers.isRight()) {
4397 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4398 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4400 return Either.right(responseFormat);
4403 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4404 // fill reduced heat env parameters List for updating
4405 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4406 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4407 currArtifact.setListHeatParameters(currentHeatEnvParams);
4409 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4410 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4411 if (updateArifactRes.isRight()) {
4412 log.debug("Failed to update artifact on graph - {}", artifactId);
4413 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4416 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4418 return Either.right(responseFormat);
4420 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4421 if (error != StorageOperationStatus.OK) {
4422 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4423 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4425 return Either.right(responseFormat);
4428 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4430 .getUniqueId(), parent.getUniqueId());
4431 if (error != StorageOperationStatus.OK) {
4432 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4433 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4435 return Either.right(responseFormat);
4439 insideEither = Either.left(currArtifact);
4440 resultOp = Either.left(insideEither);
4441 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4442 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4447 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4448 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4449 String paramName = heatEnvParam.getName();
4450 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4451 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4452 String updatedParamValue = heatEnvParam.getCurrentValue();
4453 currHeatParam.setCurrentValue(updatedParamValue);
4459 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4460 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4462 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4463 Either<ArtifactDefinition, Operation> insideEither = null;
4464 String currentHeatId = currHeatArtifact.getUniqueId();
4466 String esArtifactId = currHeatArtifact.getEsId();
4467 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4468 if (artifactFromES.isRight()) {
4469 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4470 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4471 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4472 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4473 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4476 ESArtifactData esArtifactData = artifactFromES.left().value();
4478 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4480 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4481 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4482 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4484 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4488 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4490 paramName = heatEnvParam.getName();
4491 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4492 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4494 String updatedParamValue = heatEnvParam.getCurrentValue();
4495 if (updatedParamValue == null) {
4496 updatedParamValue = heatEnvParam.getDefaultValue();
4498 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4499 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4500 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4501 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4502 .getType(), paramType.getType(), paramName);
4503 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4504 return Either.right(responseFormat);
4507 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4508 newHeatEnvParams.add(currHeatParam);
4513 if (!newHeatEnvParams.isEmpty()) {
4514 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4515 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4516 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4518 if (operationStatus.isRight()) {
4519 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4521 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4524 return Either.right(responseFormat);
4527 updatedHeatArt = operationStatus.left().value();
4529 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4530 esArtifactData.setId(updatedHeatArt.getEsId());
4532 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4535 log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4536 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4537 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4538 .getUniqueId(), responseFormat, componentType, null);
4541 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4542 log.debug(FAILED_SAVE_ARTIFACT);
4543 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4544 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4545 .getUniqueId(), responseFormat, componentType, null);
4546 resultOp = Either.right(responseFormat);
4549 insideEither = Either.left(updatedHeatArt);
4552 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4553 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4554 artifactEnvInfo.setArtifactChecksum(null);
4555 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4556 .getUniqueId(), componentType.getNodeType(), componentId);
4559 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4563 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4564 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4566 .value(), parent, componentType);
4567 if (result != ActionStatus.OK) {
4568 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4569 return Either.right(responseFormat);
4573 if (updatedHeatEnvParams.isEmpty()) {
4574 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4576 resultOp = Either.left(insideEither);
4577 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4578 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4583 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4584 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4585 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4586 return Either.right(responseFormat);
4590 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4591 StorageOperationStatus error = StorageOperationStatus.OK;
4592 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4593 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4594 List<String> groupInstancesId = null;
4595 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4596 groupInstancesId = groupsInstances.stream()
4597 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4598 .contains(artifactId))
4599 .map(GroupInstanceDataDefinition::getUniqueId)
4600 .collect(Collectors.toList());
4602 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4603 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4609 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4610 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4612 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4613 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4614 .getArtifactName(), currArtifactName);
4615 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4616 return Either.right(responseFormat);
4619 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4620 String paramName = uploadedHeatParam.getName();
4621 boolean isExistsInHeat = false;
4622 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4623 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4625 isExistsInHeat = true;
4626 uploadedHeatParam.setType(currHeatParam.getType());
4627 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4628 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4629 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4633 if (!isExistsInHeat) {
4634 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4635 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4636 return Either.right(responseFormat);
4639 return Either.left(updatedHeatEnvParams);
4642 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4643 ResponseFormat responseFormat = null;
4644 List<ComponentInstance> ris = component.getComponentInstances();
4645 for (ComponentInstance ri : ris) {
4646 if (riID.equals(ri.getUniqueId())) {
4647 return Either.left(ri);
4650 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4651 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4652 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4653 return Either.right(responseFormat);
4656 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4657 ResponseFormat responseFormat = null;
4658 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4659 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4660 if (artifactId.equals(artifact.getUniqueId())) {
4661 return Either.left(artifact);
4664 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4665 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4667 return Either.right(responseFormat);
4670 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4671 ArtifactDefinition ret;
4672 if (eitherArtifact.isLeft()) {
4673 ret = eitherArtifact.left().value();
4676 ret = eitherArtifact.right().value().getImplementationArtifact();
4682 * downloads artifact of component by UUIDs
4684 * @param componentType
4685 * @param componentUuid
4686 * @param artifactUUID
4687 * @param resourceCommonInfo
4690 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4691 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4692 Either<byte[], ResponseFormat> result;
4693 byte[] downloadedArtifact = null;
4694 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4695 if (errorWrapper.isEmpty() && component != null) {
4696 resourceCommonInfo.setResourceName(component.getName());
4697 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4699 if (errorWrapper.isEmpty()) {
4700 result = Either.left(downloadedArtifact);
4703 result = Either.right(errorWrapper.getInnerElement());
4709 * downloads an artifact of resource instance of component by UUIDs
4711 * @param componentType
4712 * @param componentUuid
4713 * @param resourceInstanceName
4714 * @param artifactUUID
4717 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4718 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4719 Either<byte[], ResponseFormat> result;
4720 byte[] downloadedArtifact = null;
4721 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4722 if (errorWrapper.isEmpty()) {
4723 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4726 if (errorWrapper.isEmpty()) {
4727 result = Either.left(downloadedArtifact);
4730 result = Either.right(errorWrapper.getInnerElement());
4736 * uploads an artifact to a component by UUID
4740 * @param componentType
4741 * @param componentUuid
4742 * @param resourceCommonInfo
4746 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4747 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4748 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4749 Component component = null;
4750 String componentId = null;
4751 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4752 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4753 String userId = request.getHeader(Constants.USER_ID_HEADER);
4755 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4756 if (getComponentRes.isRight()) {
4757 StorageOperationStatus status = getComponentRes.right().value();
4758 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4759 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4761 if (errorWrapper.isEmpty()) {
4762 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4763 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4765 if (!getComponentRes.left()
4767 .getMetadataDataDefinition()
4769 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4770 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4771 if (component != null) {
4772 componentId = component.getUniqueId();
4773 componentName = component.getName();
4776 resourceCommonInfo.setResourceName(componentName);
4778 if (errorWrapper.isEmpty()) {
4779 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4780 if (actionResult.isRight()) {
4781 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4784 return Either.right(actionResult.right().value());
4786 return Either.left(actionResult.left().value().left().value());
4788 return Either.right(errorWrapper.getInnerElement());
4791 * upload an artifact to a resource instance by UUID
4795 * @param componentType
4796 * @param componentUuid
4797 * @param resourceInstanceName
4801 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4802 ArtifactOperationInfo operation) {
4803 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4804 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4805 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4806 ArtifactDefinition uploadArtifact = null;
4807 Component component = null;
4808 String componentInstanceId;
4810 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4811 String userId = request.getHeader(Constants.USER_ID_HEADER);
4813 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4814 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4815 if (getComponentRes.isRight()) {
4816 StorageOperationStatus status = getComponentRes.right().value();
4817 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4818 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4820 if (errorWrapper.isEmpty() && !getComponentRes.left()
4822 .getMetadataDataDefinition()
4824 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4825 component = checkoutParentComponent(componentType, getComponentRes.left()
4827 .getMetadataDataDefinition()
4828 .getUniqueId(), userId, errorWrapper);
4830 if (errorWrapper.isEmpty()) {
4831 if (component == null) {
4832 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4835 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4838 if (errorWrapper.isEmpty()) {
4839 componentInstanceId = componentRiPair.getRight().getUniqueId();
4840 componentId = componentRiPair.getLeft().getUniqueId();
4841 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4843 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4844 .findParamByType(componentType));
4845 if (actionResult.isRight()) {
4846 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4849 errorWrapper.setInnerElement(actionResult.right().value());
4852 if (errorWrapper.isEmpty()) {
4853 uploadArtifact = actionResult.left().value().left().value();
4854 uploadArtifactResult = Either.left(uploadArtifact);
4857 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4859 return uploadArtifactResult;
4863 * updates an artifact on a component by UUID
4867 * @param componentType
4868 * @param componentUuid
4869 * @param artifactUUID
4873 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4874 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4875 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4876 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4877 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4878 ArtifactDefinition updateArtifact = null;
4879 Component component = null;
4880 String componentId = null;
4881 String artifactId = null;
4882 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4883 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4884 String userId = request.getHeader(Constants.USER_ID_HEADER);
4886 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4887 if (getComponentRes.isRight()) {
4888 StorageOperationStatus status = getComponentRes.right().value();
4889 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4890 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4892 if (errorWrapper.isEmpty()) {
4893 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4894 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4896 if (!getComponentRes.left()
4898 .getMetadataDataDefinition()
4900 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4901 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4902 if (component != null) {
4903 componentId = component.getUniqueId();
4904 componentName = component.getName();
4907 resourceCommonInfo.setResourceName(componentName);
4909 if (errorWrapper.isEmpty()) {
4910 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4912 if (errorWrapper.isEmpty()) {
4913 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4914 if (actionResult.isRight()) {
4915 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4918 errorWrapper.setInnerElement(actionResult.right().value());
4921 if (errorWrapper.isEmpty()) {
4922 updateArtifact = actionResult.left().value().left().value();
4923 updateArtifactResult = Either.left(updateArtifact);
4927 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4929 return updateArtifactResult;
4933 * updates an artifact on a resource instance by UUID
4937 * @param componentType
4938 * @param componentUuid
4939 * @param resourceInstanceName
4940 * @param artifactUUID
4941 * @param operation TODO
4944 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4945 ArtifactOperationInfo operation) {
4947 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4948 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4949 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4950 ArtifactDefinition updateArtifact = null;
4951 Component component = null;
4952 String componentInstanceId = null;
4953 String componentId = null;
4954 String artifactId = null;
4955 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4956 String userId = request.getHeader(Constants.USER_ID_HEADER);
4958 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4959 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4960 if (getComponentRes.isRight()) {
4961 StorageOperationStatus status = getComponentRes.right().value();
4962 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4963 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4965 if (errorWrapper.isEmpty() && !getComponentRes.left()
4967 .getMetadataDataDefinition()
4969 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4970 component = checkoutParentComponent(componentType, getComponentRes.left()
4972 .getMetadataDataDefinition()
4973 .getUniqueId(), userId, errorWrapper);
4975 if (errorWrapper.isEmpty()) {
4976 if (component == null) {
4977 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4980 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4983 if (errorWrapper.isEmpty()) {
4984 componentInstanceId = componentRiPair.getRight().getUniqueId();
4985 componentId = componentRiPair.getLeft().getUniqueId();
4986 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4988 if (errorWrapper.isEmpty()) {
4989 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4991 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4992 .findParamByType(componentType));
4993 if (actionResult.isRight()) {
4994 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4997 errorWrapper.setInnerElement(actionResult.right().value());
5000 if (errorWrapper.isEmpty()) {
5001 updateArtifact = actionResult.left().value().left().value();
5002 updateArtifactResult = Either.left(updateArtifact);
5005 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5007 return updateArtifactResult;
5011 * updates an artifact on a component by UUID
5015 * @param componentType
5016 * @param componentUuid
5017 * @param artifactUUID
5021 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
5022 String data, HttpServletRequest request, ComponentTypeEnum componentType,
5023 String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
5024 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
5025 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5026 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
5027 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5028 ArtifactDefinition updateArtifact = null;
5029 String componentId = null;
5030 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
5031 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5032 String userId = request.getHeader(Constants.USER_ID_HEADER);
5034 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5035 if (getComponentRes.isRight()) {
5036 StorageOperationStatus status = getComponentRes.right().value();
5037 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5038 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5040 if (errorWrapper.isEmpty()) {
5041 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5042 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5043 if (!getComponentRes.left()
5045 .getMetadataDataDefinition()
5047 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5048 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5049 if (component != null) {
5050 componentId = component.getUniqueId();
5051 componentName = component.getName();
5055 resourceCommonInfo.setResourceName(componentName);
5057 if (errorWrapper.isEmpty()) {
5058 Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId, interfaceUUID);
5059 if (interfaceName.isRight()) {
5060 errorWrapper.setInnerElement(interfaceName.right().value());
5062 if (errorWrapper.isEmpty()) {
5063 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5064 artifactUUID, artifactInfo, origMd5, data, interfaceName.left().value(),
5065 operationUUID, null, null);
5066 if (actionResult.isRight()) {
5067 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5070 errorWrapper.setInnerElement(actionResult.right().value());
5074 if (errorWrapper.isEmpty()) {
5075 updateArtifact = actionResult.left().value().left().value();
5076 updateArtifactResult = Either.left(updateArtifact);
5080 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5082 return updateArtifactResult;
5085 private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
5086 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
5087 if (componentStorageOperationStatusEither.isRight()) {
5088 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
5089 log.debug("Failed to fetch component information by component id, error {}", errorStatus);
5090 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5092 Component storedComponent = componentStorageOperationStatusEither.left().value();
5094 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
5095 .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
5096 if(!optionalInterface.isPresent()) {
5097 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
5099 return Either.left(optionalInterface.get().getType());
5104 * deletes an artifact on a component by UUID
5107 * @param componentType
5108 * @param componentUuid
5109 * @param artifactUUID
5110 * @param resourceCommonInfo
5111 * @param operation TODO
5114 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5115 ArtifactOperationInfo operation) {
5117 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5118 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5119 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5120 ArtifactDefinition deleteArtifact = null;
5121 Component component = null;
5122 String componentId = null;
5123 String artifactId = null;
5124 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5125 String userId = request.getHeader(Constants.USER_ID_HEADER);
5127 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5128 if (getComponentRes.isRight()) {
5129 StorageOperationStatus status = getComponentRes.right().value();
5130 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5131 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5133 if (errorWrapper.isEmpty()) {
5134 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5135 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5136 if (!getComponentRes.left()
5138 .getMetadataDataDefinition()
5140 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5141 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5142 if (component != null) {
5143 componentId = component.getUniqueId();
5144 componentName = component.getName();
5147 resourceCommonInfo.setResourceName(componentName);
5149 if (errorWrapper.isEmpty()) {
5150 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5152 if (errorWrapper.isEmpty()) {
5153 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5154 if (actionResult.isRight()) {
5155 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5158 errorWrapper.setInnerElement(actionResult.right().value());
5161 if (errorWrapper.isEmpty()) {
5162 deleteArtifact = actionResult.left().value().left().value();
5163 deleteArtifactResult = Either.left(deleteArtifact);
5166 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5168 return deleteArtifactResult;
5172 * deletes an artifact from a resource instance by UUID
5175 * @param componentType
5176 * @param componentUuid
5177 * @param resourceInstanceName
5178 * @param artifactUUID
5179 * @param operation TODO
5182 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5183 ArtifactOperationInfo operation) {
5185 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5186 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5187 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5188 ArtifactDefinition deleteArtifact = null;
5189 Component component = null;
5190 String componentInstanceId = null;
5191 String componentId = null;
5192 String artifactId = null;
5193 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5194 String userId = request.getHeader(Constants.USER_ID_HEADER);
5195 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5196 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5197 if (getComponentRes.isRight()) {
5198 StorageOperationStatus status = getComponentRes.right().value();
5199 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5200 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5202 if (errorWrapper.isEmpty() && !getComponentRes.left()
5204 .getMetadataDataDefinition()
5206 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5207 component = checkoutParentComponent(componentType, getComponentRes.left()
5209 .getMetadataDataDefinition()
5210 .getUniqueId(), userId, errorWrapper);
5212 if (errorWrapper.isEmpty()) {
5213 if (component == null) {
5214 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5217 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5220 if (errorWrapper.isEmpty()) {
5221 componentInstanceId = componentRiPair.getRight().getUniqueId();
5222 componentId = componentRiPair.getLeft().getUniqueId();
5223 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5225 if (errorWrapper.isEmpty()) {
5227 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5228 .findParamByType(componentType));
5230 if (actionResult.isRight()) {
5231 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5234 errorWrapper.setInnerElement(actionResult.right().value());
5237 if (errorWrapper.isEmpty()) {
5238 deleteArtifact = actionResult.left().value().left().value();
5239 deleteArtifactResult = Either.left(deleteArtifact);
5242 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5244 return deleteArtifactResult;
5247 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5248 String artifactId = null;
5249 ArtifactDefinition foundArtifact = null;
5250 if (instance.getDeploymentArtifacts() != null) {
5251 foundArtifact = instance.getDeploymentArtifacts()
5254 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5255 .equals(artifactUUID))
5259 if (foundArtifact == null && instance.getArtifacts() != null) {
5260 foundArtifact = instance.getArtifacts()
5263 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5264 .equals(artifactUUID))
5268 if (foundArtifact == null) {
5269 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5270 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5273 artifactId = foundArtifact.getUniqueId();
5278 @SuppressWarnings("unchecked")
5279 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5280 Map<String, String> existingEnvVersions) {
5281 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5283 .getDeploymentResourceInstanceArtifacts();
5284 if (deploymentResourceArtifacts == null) {
5285 log.debug("no deployment artifacts are configured for generated artifacts");
5286 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5288 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5289 if (placeHolderData == null) {
5290 log.debug("no env type {} are configured for generated artifacts", envType);
5291 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5294 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5295 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5296 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5297 if (createArtifactPlaceHolder.isRight()) {
5298 return Either.right(createArtifactPlaceHolder.right().value());
5300 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5301 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5302 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5303 artifactHeatEnv.setTimeout(0);
5304 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5305 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5306 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5307 ArtifactDefinition heatEnvPlaceholder;
5308 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5309 if (parentType != NodeTypeEnum.ResourceInstance) {
5310 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5311 .getUniqueId(), parentType, parentId);
5312 if (addHeatEnvArtifact.isRight()) {
5313 log.debug("failed to create heat env artifact on resource instance");
5314 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5316 .value(), false), "", null));
5318 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5321 heatEnvPlaceholder = artifactHeatEnv;
5322 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5323 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5326 ComponentTypeEnum componentType = component.getComponentType();
5327 if (parentType == NodeTypeEnum.ResourceInstance) {
5328 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5330 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5331 new ResourceCommonInfo(parentName, componentType.getValue()),
5332 ResourceVersionInfo.newBuilder().build(),
5333 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5334 null, heatEnvPlaceholder, null);
5335 return Either.left(heatEnvPlaceholder);
5338 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5339 if (artifact.getListHeatParameters() == null) {
5342 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5343 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5344 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5345 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5346 heatEnvParameter.setCurrentValue(null);
5347 heatEnvParameters.add(heatEnvParameter);
5349 artifactDefinition.setListHeatParameters(heatEnvParameters);
5352 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5353 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5354 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5355 String name = heatArtifact.getArtifactName();
5358 name = heatArtifact.getArtifactLabel();
5359 fileName = name + "." + envExtension;
5362 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5364 heatEnvArtifact.setArtifactName(fileName);
5367 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5368 if (null != existingEnvVersions) {
5369 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5370 if (null != prevVersion) {
5371 heatEnvArtifact.setArtifactVersion(prevVersion);
5377 * Handles Artifacts Request For Inner Component
5379 * @param artifactsToHandle
5382 * @param vfcsNewCreatedArtifacts
5385 * @param inTransaction
5388 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5389 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5391 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5392 ComponentTypeEnum componentType = component.getComponentType();
5393 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5394 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5395 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5399 for (ArtifactDefinition artifact : artifactsToHandle) {
5400 originData = buildJsonStringForCsarVfcArtifact(artifact);
5401 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5402 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5403 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5404 if (actionResult.isRight()) {
5405 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5406 .getName(), actionResult.right().value());
5407 errorWrapper.setInnerElement(actionResult.right().value());
5408 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5409 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5413 uploadedArtifacts.add(actionResult.left().value().left().value());
5415 if (errorWrapper.isEmpty()) {
5416 handleArtifactsResult = Either.left(uploadedArtifacts);
5419 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5422 catch (Exception e) {
5423 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5424 handleArtifactsResult = Either.right(responseFormat);
5425 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5427 return handleArtifactsResult;
5430 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5431 ComponentInstance componentInstance = null;
5432 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5433 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5434 if (errorWrapper.isEmpty()) {
5435 componentInstance = component.getComponentInstances()
5437 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5438 .equals(normalizedName))
5441 if (componentInstance == null) {
5442 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5444 .getValue(), component.getName()));
5445 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5448 return componentInstance;
5451 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5453 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5454 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5455 ComponentInstance componentInstance = component.getComponentInstances()
5457 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5458 .equals(normalizedName))
5461 if (componentInstance == null) {
5462 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5464 .getValue(), component.getName()));
5465 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5468 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5470 return relatedComponentComponentInstancePair;
5473 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5474 ComponentInstance componentInstance;
5475 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5476 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5477 if (errorWrapper.isEmpty()) {
5478 componentInstance = component.getComponentInstances()
5480 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5483 if (componentInstance == null) {
5484 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5486 .getValue(), component.getName()));
5487 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5490 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5493 return relatedComponentComponentInstancePair;
5496 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5498 byte[] downloadedArtifact = null;
5499 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5500 List<ArtifactDefinition> artifactsList = null;
5501 ArtifactDefinition deploymentArtifact = null;
5502 if (artifacts != null && !artifacts.isEmpty()) {
5503 artifactsList = artifacts.values()
5505 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5506 .equals(artifactUUID))
5507 .collect(Collectors.toList());
5509 if (artifactsList == null || artifactsList.isEmpty()) {
5510 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5511 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5513 if (errorWrapper.isEmpty()) {
5514 deploymentArtifact = artifactsList.get(0);
5515 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5516 if (downloadArtifactEither.isRight()) {
5517 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5518 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5521 if (errorWrapper.isEmpty()) {
5522 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5523 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5525 return downloadedArtifact;
5528 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5529 Component component = null;
5530 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5531 if (getComponentRes.isRight()) {
5532 StorageOperationStatus status = getComponentRes.right().value();
5533 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5534 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5537 component = getComponentRes.left().value();
5542 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5543 Component component = null;
5544 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5545 if (getComponentRes.isRight()) {
5546 StorageOperationStatus status = getComponentRes.right().value();
5547 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5548 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5551 List<Component> value = getComponentRes.left().value();
5552 if (value.isEmpty()) {
5553 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5554 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5555 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5558 component = value.get(0);
5564 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5565 String artifactId = null;
5566 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5567 StorageOperationStatus storageStatus;
5568 ArtifactDefinition latestArtifact = null;
5569 List<ArtifactDefinition> artifacts = null;
5570 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5571 if (getArtifactsRes.isRight()) {
5572 storageStatus = getArtifactsRes.right().value();
5573 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5574 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5575 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5577 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5579 if (errorWrapper.isEmpty()) {
5580 artifacts = getArtifactsRes.left()
5584 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5585 .equals(artifactUUID))
5586 .collect(Collectors.toList());
5587 if (artifacts == null || artifacts.isEmpty()) {
5588 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5589 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5592 if (errorWrapper.isEmpty()) {
5593 latestArtifact = artifacts.stream().max((a1, a2) -> {
5594 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5595 if (compareRes == 0) {
5596 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5597 .getLastUpdateDate());
5601 if (latestArtifact == null) {
5602 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5603 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5606 if (errorWrapper.isEmpty()) {
5607 artifactId = latestArtifact.getUniqueId();
5612 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5614 Component component = null;
5615 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5616 if (getUserRes.isRight()) {
5617 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5620 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5622 if (errorWrapper.isEmpty()) {
5623 User modifier = getUserRes.left().value();
5624 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5625 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5626 if (checkoutRes.isRight()) {
5627 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5628 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5629 errorWrapper.setInnerElement(checkoutRes.right().value());
5632 component = checkoutRes.left().value();
5638 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5639 Map<String, Object> json = new HashMap<>();
5640 String artifactName = artifact.getArtifactName();
5641 json.put(Constants.ARTIFACT_NAME, artifactName);
5642 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5643 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5644 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5645 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5646 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5647 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5648 return gson.toJson(json);
5652 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5653 this.nodeTemplateOperation = nodeTemplateOperation;